[英]5xx or 4xx error with “No 'Access-Control-Allow-Origin' header is present”
My browser is logging the following message in the devtools console:我的浏览器在 devtools 控制台中记录以下消息:
No 'Access-Control-Allow-Origin' header is present on the requested resource.… The response had HTTP status code 503.
请求的资源上不存在“Access-Control-Allow-Origin”标头……响应的 HTTP 状态代码为 503。
Background : I have two apps.背景:我有两个应用程序。 One that is an Express Node application connected to a Mongo database.
一个是连接到 Mongo 数据库的 Express Node 应用程序。 The other is a basic web application that makes
POST
requests to the Node application via the Fetch API to get data from Mongo.另一个是基本的 Web 应用程序,它通过 Fetch API 向 Node 应用程序发出
POST
请求,以从 Mongo 获取数据。
Issue : Though I receive no CORS
errors on my local machine, I am given the error below as soon as I deploy my basic web application to production.问题:虽然我在本地机器上没有收到
CORS
错误,但一旦我将基本 Web 应用程序部署到生产环境,我就会收到以下错误。 The web application that makes a POST
request to the Node app and gives me this:向 Node 应用程序发出
POST
请求并为我提供以下信息的 Web 应用程序:
The POST
request does seem to work and the data is saved into Mongo but this error is being marked as a "Critical Error" in Heroku and is quite annoying. POST
请求似乎有效并且数据已保存到 Mongo 中,但此错误在 Heroku 中被标记为“严重错误”并且非常烦人。
I realize that I could set the no-cors
option in Fetch but I believe that it is required since I am making a request to a url that is different than the origin.我意识到我可以在 Fetch 中设置
no-cors
选项,但我相信这是必需的,因为我正在向与原点不同的 url 发出请求。 Right?对?
Express Node App Code Express 节点应用程序代码
In my app.js
file I have set the correct headers to ensure that other applications can make requests from different origins在我的
app.js
文件中,我设置了正确的标头以确保其他应用程序可以从不同来源发出请求
app.js应用程序.js
// Add headers so we can make API requests
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
routes/api/api.js路线/api/api.js
router.post('/users/:url/upload-csv/:csv_name', (req, res) => {
let csv_name = req.params.csv_name;
let csv_string = csv_name+req.body.csv_string;
User.findOne({url: req.params.url})
.then((user) => {
if (user.csv_files.length === 0) {
user.csv_files.push(csv_string);
} else {
let foundExistingCSV = false;
for (var i = 0; i < user.csv_files.length; i++) {
if (user.csv_files[i].includes(csv_name)) {
foundExistingCSV = true;
user.csv_files[i] = csv_string;
break;
}
}
if (!foundExistingCSV) user.csv_files.push(csv_string);
}
user.markModified('csv_files');
user.save();
res.status(204);
})
.catch((err) => {
console.log(err);
res.status(400);
});
});
Basic Web App Code基本的 Web 应用程序代码
POST
request I am making我正在发出
POST
请求
utils.js实用程序.js
utils.exportToMongo = functions(table, name) {
var exportPlugin = table.getPlugin('exportFile');
var csv_string = exportPlugin.exportAsString('csv');
// Upload the CSV string and its name to Users DB
fetch(`${utils.fetchUserURL()}/upload-csv/${name}`, {
method: 'POST',
body: JSON.stringify({csv_string: csv_string}),
headers: new Headers({
'Content-Type': 'application/json',
Accept: 'application/json',
})
}).then((res) => {
return {};
}).catch((error) => {
console.log(error);
return {};
});
}
How can I remove the 503
error?如何消除
503
错误? Any insight would be greatly appreciated!任何见解将不胜感激!
An HTTP 5xx
error indicates some failure on the server side. HTTP
5xx
错误表示服务器端出现某些故障。 Or it can even indicate the server just isn't responding at all — eg, a case might be, your backend tries to proxy a request to a server on another port, but the server is not even be up and listening on the expected port.或者它甚至可以表明服务器根本没有响应——例如,一种情况可能是,你的后端试图将请求代理到另一个端口上的服务器,但服务器甚至没有启动并监听预期的端口.
Similarly, a 4xx
indicates some problem with the request prevented the server from handling it.类似地,
4xx
表示请求的某些问题阻止了服务器处理它。
To confirm, you can try making the same request using curl, or Postman, or something, and see if you get a 2xx
success response for the request, rather than a 5xx
or 4xx
.要确认,您可以尝试使用 curl 或 Postman 或其他方式发出相同的请求,然后查看您是否收到
2xx
请求的成功响应,而不是5xx
或4xx
。
Regardless, if you see a 5xx
or 4xx
error on the client side, some message should get logged on the server side to indicate what failed and why.无论如何,如果您在客户端看到
5xx
或4xx
错误,则应该在服务器端记录一些消息以指示失败的原因和原因。 So to identify what triggered the 5xx
/ 4xx
error, check server logs to find messages the server logged before it sent the error.因此,要确定触发
5xx
/ 4xx
错误的原因,请检查服务器日志以查找服务器在发送错误之前记录的消息。
As far as CORS error messages go, it's expected that in most cases for a 5xx
or 4xx
error, servers won't add the Access-Control-Allow-Origin
response header to the response;就 CORS 错误消息而言,预计在大多数情况下,对于
5xx
或4xx
错误,服务器不会将Access-Control-Allow-Origin
响应标头添加到响应中; instead the server most likely will only send that header for 2xx
and 3xx
(redirect) responses.相反,服务器很可能只会为
2xx
和3xx
(重定向)响应发送该标头。
So if you get the cause of an 5xx
/ 4xx
error solved such that you can get a success response, you may find your CORS config is already working fine and you've got nothing left to fix.因此,如果您解决了
5xx
/ 4xx
错误的原因,从而获得了成功响应,您可能会发现您的 CORS 配置已经正常工作并且您没有什么需要修复的了。
I had the same issue, the server doesn't support cross origin request.我有同样的问题,服务器不支持跨源请求。 The API developer should change Access-Control-Allow-Origin to * (means from any origin).sometimes jsonp request will bypass, if its not working, google chrome provides plugins to change origin plugin
API 开发人员应将 Access-Control-Allow-Origin 更改为 *(表示来自任何来源)。有时 jsonp 请求将绕过,如果它不起作用,谷歌浏览器提供插件来更改来源插件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.