【发布时间】:2018-05-30 12:40:11
【问题描述】:
我遇到了与 CORS 相关的问题(我认为),当我从邮递员发送登录帖子请求时,它会成功。当我尝试使用我的 Angular 2 前端应用程序登录时,请求状态似乎是 200,但没有任何反应,并且在控制台中我收到一条奇怪的消息,提示我的 localhost:4200 是不允许的,我该如何解决这个问题?
Angular http 方法
authenticateUser(user){
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:3000/api/authenticate', user, {headers: headers})
.map(res => res.json());
}
如果这是与快递相关的问题,这里是我的快递代码:
const express = require("express")
const bodyParser = require("body-parser")
const logger = require('morgan')
const api = require("./api/api")
const path = require('path')
const secret = require('./models/secrets')
const expressJWT = require('express-jwt')
const cors = require('cors');
const app = express()
app.set("json spaces", 2)
app.use(logger("dev"))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(expressJWT({secret: secret}).unless({path : ['/api/authenticate', '/api/register']}))
app.use("/api/", api)
app.use(function (req, res, next) {
var err = new Error('Not Found')
err.status = 404
next(err)
})
app.use(function (err, req, res, next) {
console.error(err.status)
res.status(err.status || 500)
res.json({ msg: err.message, status: err.status })
})
// Body Parser middleware
app.use(bodyParser.json());
// CORS middleware
app.use(cors());
// set static folder
app.use(express.static(path.join(__dirname, 'public')));
//Call this to initialize mongoose
function initMongoose(dbConnection) {
require("./db/mongooseConnect")(dbConnection)
}
app.initMongoose = initMongoose
module.exports = app
/authenticate 的路由看起来像这样
// Authenticate
router.post('/authenticate', (req, res, next) => {
const username = req.body.username;
const password = req.body.password;
User.getUserByUsername(username, (err, user) => {
if (err) throw err;
if (!user) {
return res.json({ success: false, msg: 'User not found' });
}
User.comparePassword(password, user.password, (err, isMatch) => {
if (err) throw err;
if (isMatch) {
const token = jwt.sign({data: user}, secret, {
expiresIn: 604800 // 1 week
});
res.json({
success: true,
token: 'Bearer ' + token,
user: {
id: user._id,
name: user.name,
username: user.username,
email: user.email
}
});
} else {
return res.json({ success: false, msg: 'Wrong password' });
}
});
});
});
【问题讨论】:
标签: node.js angular express cors