节点快速网站与 REST 身份验证 API - CORS 问题



我是nodejs + Express的新手,但我正在尝试构建一个非常快速的概念验证网站,允许用户通过REST API进行身份验证。

我遇到了 CORS 问题,尽管安装了 cors 模块并按照文档中的建议使用它,但我仍然收到以下错误:

在 xxx 上访问 XMLHttpRequest 已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查: "访问控制允许源"标头具有值 "https://www.example.com"不等于提供的原产地。

这是我的(简化(代码:

应用.js

const express = require('express');
const expressLayouts = require('express-ejs-layouts');
const cors = require('cors');
compression = require('compression'),
shouldCompress = (req, res) => {
if (req.headers['x-no-compression']) {
// don't compress responses if this request header is present
return false;
}
// fallback to standard compression
return compression.filter(req, res);
};
const app = express();

// EJS
app.use(expressLayouts);
app.set('view engine', 'ejs');
// Parsing related
app.use(express.urlencoded( { extended: false })); //Parse URL-encoded bodies
app.use(express.json()); //Used to parse JSON bodies
app.use(compression({
filter:shouldCompress,
threshold: 3
}));
app.use(express.static('public'));
app.disable('x-powered-by');

// Using the flash middleware provided by connect-flash to store messages in session
// and displaying in templates
const flash = require('connect-flash');
app.use(flash());
// Sessions
const session = require('express-session');
app.use(session({
secret: 'fat cat 42',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}));
// Initialize Passport and restore authentication state, if any, from the session.
const passport = require('passport');
require ('./config/passport')(passport);
app.use(passport.initialize());
app.use(passport.session())
// Routes
app.use('/', require('./routes/index'));
app.use('/member', require('./routes/users'));

const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`Server started on port: ${PORT}`));

用户.js

const express = require('express');
const router = express.Router();
const passport = require('passport');
require ('../config/passport')(passport);

router.post('/signin', passport.authenticate('facebook', {
successRedirect : '/home',
failureRedirect : '/'
}));
module.exports = router;

这是使 AJAX POST 的视图的脚本部分

主页.ejs

$(document).ready(function(){
$('#demo').click(function(e){
$.ajax({
method: "POST",
url: "/member/signin",
data: {
"source": $(this).attr('id')
},
dataType: "json",
timeout: 5000 // 5000ms
}).done(function(data) {
// is called if request is successful
console.log('Success:' + data);
}).fail(function(jqXHR, status) {
// is called if request fails or timeout is reached
alert('Request could not complete: ' + status);
});
});
});

如何解决此问题以使 AJAX 调用正常工作?

本质上,您需要允许跨站点源请求。 您可以通过在节点服务器前面使用一些代理(如 nginx(正常设置access-control-headers来做到这一点,如下所示(不建议将 node 直接暴露在端口 80 上(

#nginx config
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, HEAD, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Requested-With';
return 204;
}

如果你有 ExpressJS,你可以使用这个 CORS 中间件

var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.post('/signin/', function (req, res, next) {
// ....
})

相关内容

  • 没有找到相关文章

最新更新