目前我的Angular2前端在localhost:3000
上运行,NodeJS后端(基于KrakenJS)在localhost:8000
上运行。当我输入凭据时,我称之为this.http.post('http://localhost:8000/login', body, { headers: contentHeaders })
api,但我在Chrome中收到以下回复:
XMLHttpRequest cannot load http://localhost:8000/login. The request was redirected to 'http://localhost:8000/', which is disallowed for cross-origin requests that require preflight.
但是当我调用this.http.post('http://localhost:8000/register', body, { headers: contentHeaders })
时,一切正常并且完成所有注册魔术(散列pswd,将数据存储在database..etc中。)。
这是来自(register.js)的简单寄存器API:
router.post('/', function (req, res) {
if (req.body.email && req.body.password) {
var User = require('../../models/user');
User.create({
name: req.body.name,
email: req.body.email,
password: req.body.password
}).then(
function() {
res.render('user/registered', {registered: true});
},
function() {
res.render('user/registered', {registered: false});
}
);
} else {
res.render('user/registered', {registered: false});
}
});
以下是来自(login.js)的登录api:
router.post('/', function (req, res) {
passport.authenticate('local', {
successRedirect: req.session.goingTo || '/',
failureRedirect: '/login',
failureFlash: true
})(req, res);
});
答案 0 :(得分:0)
使用以下命令在主服务器文件中启用CORS:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});