Node.js Express.js和CORS
我使用Node.js Express.js和CORS,node.js,express,cors,backend,Node.js,Express,Cors,Backend,我使用react.js构建了一个前端,并使用express.js构建了一个API服务器。为了处理CORS,我使用CORS包作为以下示例: var passport = require("passport"); const express = require('express'); const cors = require('cors'); const app = express(); app.use(cors()); app.use('/route1', passport.authentica
react.js
构建了一个前端,并使用express.js
构建了一个API服务器。为了处理CORS,我使用CORS
包作为以下示例:
var passport = require("passport");
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use('/route1', passport.authenticate('jwt', {session: false}), route1)
app.use('/route2', passport.authenticate('jwt', {session: false}), route2)
app.use('/route3', passport.authenticate('jwt', {session: false}), route3)
app.use(function(req, res, next) { /* catch 404 and forward to error handler */
next(createError(404));
});
app.listen(app.get('port'), () => {
logger.info('Server started')
})
所有路由都工作正常,直到对同一路由发出两个连续请求。例如:
POST example.com/route1
GET example.com/route1
POST example.com/route1
GET example.com/route1/example
我将获取错误请求的资源上不存在“Access Control Allow Origin”标题。
在get请求的浏览器控制台中。但如果我将路径更改为,例如:
POST example.com/route1
GET example.com/route1
POST example.com/route1
GET example.com/route1/example
它起作用了
这两个服务器都在apache Web服务器上运行。我的后端服务器是通过https访问的,它会将其重定向到http上运行的nodejs服务器
我做错了什么?多谢各位
编辑:如所问,这里有一段route1
const express = require('express')
const router = express.Router()
const errors = require('./error_handler');
router.post('/', async (req, res, next) => {
const result =
/* DB Middleware */
.catch((err) => errors.errorHandler(err,res))
if(!res.headersSent) /* Making this condition to check if errorHandler() already sent an error response */
res.send(result);
})
router.get('/', async (req, res, next) => {
if(req.query.course === undefined)
res.send(400);
let result =
/* DB Middleware */
.catch((err) => errors.errorHandler(err,res))
if(!res.headersSent)
res.send(result)
})
module.exports = router
不久前我在一个项目中遇到了这个问题,我把它添加到我的应用程序中,并为我工作。这是因为您需要允许每个来源访问您的项目
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
如果不起作用,请尝试将crossDomain添加到您的需求中,如:
$.ajax({
url: url,
crossDomain: true,
data: form,
dataType: 'json',
success: function(data) {
console.log(data);
},
type: 'POST'
});
在app.js中包含以下代码:
var express = require('express')
var cors = require('cors')
var app = express()
var whitelist = ['http://example1.com', 'http://example2.com']
var corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
app.use(cors(corsOptions));
您可以创建一个通用的中间件,它将在您想要支持cors的任何API上使用
var AllowedOrigins = ['http://example1.com', 'http://example2.com'];
setCorsHeaders: function (req, res, next) {
let requestDomain = req.headers.Origin;
AllowedOrigins.forEach(allowedOrigin => {
if (requestDomain === allowedOrigin) {
res.setHeader('Access-Control-Allow-Origin', requestDomain);
res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
}
});
if (req.method === 'OPTIONS') {
res.status(200);
} else {
next();
}
}
您可以共享route1文件中的代码片段吗?只需使用ITI@spacecows片段进行编辑,确认apache severe正在将所有响应头从http上运行的node.js应用转发到http上运行的客户端browser@oseme_techguy我不是管理员,但我会尽快和他核实。但是如果这就是原因,它不是在其他情况下都会失败,而不仅仅是在特定情况下吗?从这里的包描述中可以看出->默认配置相当于:``{“origin”:“*”,“methods”:“GET,HEAD,PUT,PATCH,POST,DELETE”,“preflightContinue”:false,“options successstatus”:204}“``这意味着默认配置不考虑使用/需要动词或飞行前选项的情况。我昨天尝试了该解决方案,我现在尝试它只是为了确保,但现在每个请求都会收到错误
请求的资源上没有“Access Control Allow Origin”头。
或crossDomain?我是axios,不是ajax,所以我尝试使用跨域作为axios.defaults.crossDomain=true
,但它也不起作用。