使用middleware...
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()
})
但请确保您在您的 API 方法之前使用它。像这样:
const app = express()
// middleware
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()
})
// api
app.get('/user', (req, res, next) => {
service.doSomething
.then(data => res.send(data))
.catch(next)
})
app.use(handleError)
我花了一段时间才弄明白。我没有在任何地方看到它,所以添加它以补充以前的答案。