5xx或4xx错误,显示“没有'Access-Control-Allow-Origin'标头" [英] 5xx or 4xx error with “No 'Access-Control-Allow-Origin' header is present”

查看:147
本文介绍了5xx或4xx错误,显示“没有'Access-Control-Allow-Origin'标头"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的浏览器正在devtools控制台中记录以下消息:

My browser is logging the following message in the devtools console:

所请求的资源上没有"Access-Control-Allow-Origin"标头.…响应的HTTP状态码为503.

No 'Access-Control-Allow-Origin' header is present on the requested resource.… The response had HTTP status code 503.

背景:我有两个应用.一个是连接到Mongo数据库的Express Node应用程序.另一个是基本的Web应用程序,它通过Fetch API向Node应用程序发出POST请求,以从Mongo获取数据.

Background: I have two apps. One that is an Express Node application connected to a Mongo database. The other is a basic web application that makes POST requests to the Node application via the Fetch API to get data from Mongo.

问题:尽管我在本地计算机上未收到任何CORS错误,但是在将基本的Web应用程序部署到生产环境后,我收到以下错误消息. Web应用程序向Node应用程序发出POST请求,并给我以下信息:

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. The web application that makes a POST request to the Node app and gives me this:

POST请求似乎确实起作用,并且数据已保存到Mongo中,但是此错误在Heroku中被标记为严重错误",非常令人讨厌.

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.

我意识到我可以在Fetch中设置no-cors选项,但是我认为这是必需的,因为我正在向不同于原始地址的url发出请求.对吧?

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. Right?

Express Node应用代码

在我的app.js文件中,我设置了正确的标头,以确保其他应用程序可以发出来自不同来源的请求

In my app.js file I have set the correct headers to ensure that other applications can make requests from different origins

app.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

routes/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);
    });
});

基本Web应用代码

POST请求我正在

utils.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 {};
  });
}

如何清除503错误?任何见识将不胜感激!

How can I remove the 503 error? Any insight would be greatly appreciated!

推荐答案

HTTP 5xx错误表明服务器端发生了某些故障.甚至可能表明服务器根本没有响应-例如,一种情况可能是,您的后端试图将请求代理到另一个端口上的服务器,但是服务器甚至没有启动并正在侦听预期的请求端口.

An HTTP 5xx error indicates some failure on the server side. Or it can even indicate the server just isn’t responding at all — for example, 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.

类似地,4xx表示请求存在一些问题,导致服务器无法处理该请求.

Similarly, a 4xx indicates some problem with the request prevented the server from handling it.

为进行确认,您可以尝试使用其他客户端(curl,Postman或其他任何设备)发出相同的请求,并查看是否收到请求的2xx成功响应,而不是5xx.

To confirm, you can try making the same request using a different client (curl, Postman, or whatever), and see if you get a 2xx success response for the request, rather than a 5xx or 4xx.

无论如何,如果您在客户端看到5xx4xx错误,则应该在服务器端记录一些消息,以指示失败的原因和原因.因此,要确定是什么触发了5xx/4xx错误,请先查看服务器日志以查找服务器在发送错误之前记录的消息.

Regardless, if you’re seeing a 5xx or 4xx error on the client side, some message should be getting logged on the server side to indicate what failed and why. So to identify what triggered the 5xx/4xx error, start by looking at the server logs to find messages the server logged before it sent the error.

就CORS错误消息而言,预计在大多数情况下,当发生5xx4xx错误时,服务器不会在响应中添加Access-Control-Allow-Origin响应标头,而服务器很可能会在响应中添加Access-Control-Allow-Origin响应标头.仅发送2xx3xx(重定向)响应的标头.

As far as CORS error messages go, it’s expected that in most cases when a 5xx or 4xx error occurs, servers won’t add the Access-Control-Allow-Origin response header to the response — instead the server most likely will only send that header for 2xx and 3xx (redirect) responses.

因此,如果您解决了5xx/4xx错误的原因,从而可以得到成功的响应,则可能会发现您的CORS配置已经按预期工作,没有任何可修复的地方.

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 configuration is already working as expected and you’ve got nothing left to fix.

这篇关于5xx或4xx错误,显示“没有'Access-Control-Allow-Origin'标头"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆