当我尝试从前端项目获取请求时,我收到此错误
从源“http://10.3.0.112:5488”访问“http://10.3.0.112:41052/operations”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。
上面的代码是我的 nginx 配置文件。
events {}
http {
upstream tag {
server tag:41038;
server tag:42038;
}
server {
listen 41038;
listen 42038;
location / {
proxy_pass http://tag;
}
}
upstream order {
server order:41052;
server order:42052;
server order:43052;
}
server {
listen 41052;
listen 42052;
listen 43052;
location / {
proxy_pass http://order;
}
}
}
最后一个来自我的前端应用程序ajax请求
function allCompletedJobOrders() {
requestStarted()
if(hasSelectableProps.length > 0) {
let stationIds = hasSelectableProps.map(item => item.id)
completedJobOrders = []
jobOrders = []
$.ajax({
type: "GET",
url: `http://${getConfig('serverAddress')}:41052/job-orders?stationIds=${stationIds}`,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': auth ? `${auth.token_type} ${auth.access_token}` : null
},
success: function (data) {
if(data.length > 0){
data.filter(item => item.startTime && item.endTime).forEach(jobOrder => {
completedJobOrders.push({
id: jobOrder.id,
code:jobOrder.code,
stationId:jobOrder.stationId,
startTime:jobOrder.startTime,
endTime: jobOrder.endTime,
targetAmount:jobOrder.targetAmount,
})
})
data.filter(item => !item.endTime).forEach(jobOrder => {
jobOrders.push({
id: jobOrder.id,
code:jobOrder.code,
stationId:jobOrder.stationId,
startTime:jobOrder.startTime,
endTime: jobOrder.endTime,
targetAmount:jobOrder.targetAmount,
operationId: jobOrder.operations[0] ? jobOrder.operations[0].operationId : [],
})
})
requestEnded()
let jobOrderIds = jobOrders.map(item => item.id)
getRollersByIds(jobOrderIds)
}
}
})
}
}
我尝试更改我的 nginx 配置文件,但没有成功。我需要完成前端应用程序的所有请求
COR 问题与 nginx 无关,而是我们需要在后端应用的配置。
以下是 Node.js 中的示例。
var express = require('express')
var cors = require('cors')
var app = express()
var whitelist = ['http://10.3.0.112:5488', 'http://example1.com']
var corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
app.get('/products/:id', cors(corsOptions), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for a whitelisted domain.'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})