【问题标题】:when I hit my node JS API from Heroku live server, CORS policy error is coming当我从 Heroku 实时服务器访问我的节点 JS API 时,CORS 策略错误即将到来
【发布时间】:2021-11-20 05:33:54
【问题描述】:

当我从 Angular 应用程序(在本地设置中)点击我的节点 js API 并将我的节点 js API 保存在 Heroku 实时服务器中时,我收到了这个错误。 CORS 政策:没有“访问控制允许来源”, 但同时,当我将 API 保存在 AWS 服务器或本地服务器设置中时,我没有收到任何错误。一切正常。 我安装了cors并使用了setHeader,在我的API中,我附上了错误和代码的图像,请帮我解决这个问题。

我正在将此代码用于allow-access-header

    // Add headers
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, OPTIONS, PUT, HEAD,PATCH, DELETE');

   // Request headers you wish to allow
   res.setHeader('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization');

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

我在这里使用这个 API

app.get("/getNoOfUsersGuardians",(request, response) => {
    let userArr = [];
    let _userData = [];
    database.collection("_User").find().toArray((error, result) => {
        if(error) {
            return response.json({ status: false, data: '', message: error });
        }
        _userData = result;
        var j = 1;
    // console.log(_userData[0]);
       for (var i = 0; i < _userData.length; i++){
            var userId = "_User$"+_userData[i]['_id'];
            let name=_userData[i]['name'];
            let username=_userData[i]['username'];
            let userEmail = _userData[i]['email'];
            let mobileno=_userData[i]['phoneNumber'];
            let phonecountrycode=_userData[i]['phoneCountryCode'];
            let _updated_At =_userData[i]['_updated_at'];
            database.collection("GuardianInvitation").find({_p_fromUser: userId, status:"accepted"}).count((error, result1)=>{
                if(result1)
                {
                    database.collection("_Session").findOne({_p_user: userId}, function(err, resultdevice) {
                        if (resultdevice) {
                   tempuserArr={ };
                   tempuserArr.userid=userId;
                   tempuserArr.username=username;
                   tempuserArr.name=name;
                   tempuserArr.mobileno=mobileno;
                   tempuserArr.userEmail=userEmail;
                   tempuserArr.phoneCountryCode=phonecountrycode;
                   tempuserArr._updated_at = _updated_At;
                   tempuserArr.NoofGuardian=result1;
                   tempuserArr.device=resultdevice["device"];
                   userArr.push(tempuserArr);
                         }
                     });
                }
                j++;
                if(_userData.length == j){
                    if(userArr.length > 0){
                        response.send({ status: true, data: userArr, message: 'User liSt found that have Number of guardians' });
                    } else {
                        response.send({ status: false, data: "", message: 'Guardians list not found' });
                    }
                }
            });
        }
    });
});

请看这里的图片... Console Error Image

【问题讨论】:

  • 你为什么不从 npm 安装 cors 包,导入它 const cors = require('cors') 并像这样使用它:app.use(cors())
  • @hacKaTun3s 我已经安装了cors 并使用var cors = require('cors'); 并像这样使用app.use(cors());
  • 那么你为什么要使用这个代码呢? - “我正在将此代码用于允许访问标头”
  • 当我们从另一台服务器访问 API 到另一台服务器时,错误就像 cross-origin-access-header 一样,这就是为什么我们使用此代码并且错误不会出现,但在我的情况下,错误只会出现 heroku服务器,当我点击这个 API 时,没有出现服务器错误

标签: javascript node.js angular heroku cors


【解决方案1】:

您可以尝试像这样添加节点 cors 选项

const corsOptions = {
 origin: '*',
 methods: [
  'GET',
  'POST',
 ],
 allowedHeaders: [
  'Content-Type',
 ],
};
app.use(cors(corsOptions));

【讨论】:

  • 我在服务器端使用了您的代码,但有时会遇到此问题,我该如何解决?
  • 如果您使用这样的节点 cors,请删除提到的向应用程序添加部分的标头。还将所有方法和标头添加到 corsOption 对象。您可以尝试两种方式,无论是这种方式还是您提到的方式。但是您需要确保在定义路由之前添加它。
猜你喜欢
  • 1970-01-01
  • 2023-04-06
  • 2021-09-19
  • 2021-10-02
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2022-01-25
  • 1970-01-01
相关资源
最近更新 更多