Node.js CORS错误

lstz6jyr  于 2023-02-15  发布在  Node.js
关注(0)|答案(6)|浏览(146)

我使用Node作为后端服务器,Angular 4作为前端。我尝试通过SOAP协议发送查询结果。该功能工作正常,但在浏览器中安装了CORS插件。但如果没有这些插件,我如何解决它?
我已经搜索了一些解决方案,我已经在我的节点文件中安装了CORS包,并对我的server.js文件做了以下事情。

//## =======BASE SETUP=======

const arangojs = require('arangojs');
const express = require('express');
const aqlQuery = arangojs.aqlQuery;
const bodyParser = require('body-parser');

var cors = require('cors');
var app = express();
app.use(cors());
app.use(function(req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
  res.setHeader('Access-Control-Allow-Credentials', true);
  next();
});

但它没有帮助。错误仍然存在。我该如何解决这个错误。我已经发布了我的服务器端代码如下:

var soap = require('strong-soap').soap;
var http = require('http');
var fs = require('fs');

function dbQuery() {
  var response = db.query(aqlQuery `
                 LET startVertex = (FOR doc IN spec
                 FILTER doc.serial_no == '"123456abcde"'
                 LIMIT 2
                 RETURN doc
                 )[0]

                FOR v IN 1 ANY startVertex belongs_to
                RETURN v.ip`, {
    bindVar1: 'value',
    bindVar2: 'value',
  });
  console.log("response is " + response);
  return response;

}

function main2() {
  var result2 = dbQuery();

  return result2.then(function(test) {

    console.log("test is " + JSON.stringify(test._result));
    var IP = test._result.filter(Boolean);
    console.log("Ip is " + IP);

    var xml = require('fs').readFileSync('check_username.wsdl', 'utf8');
    var soap_msg = '<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:examples:CheckUserNameService"$
    '<soapenv:Header/>' + '<soapenv:Body>' + '<urn:CheckUserNameResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' + '<status xsi:type="xsd:string">' + JSON.stringify(test._result) + '</status>' + '</urn:CheckUserNameResponse>' +
      '</soapenv:Envelope>';

    var server = http.createServer(function(request, response) {
      response.end(soap_msg);
    });

    var port = 8000;
    server.listen(port);
    var soapServer = soap.listen(server, '/test', xml);
    console.log('SOAP service listening on port ' + port);
  });
}
main2();

az31mfrm

az31mfrm1#

现在可能有点晚了,但我希望它能帮助到一些人。对我来说,我通过添加以下代码解决了node.js中的CORS策略:

app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

在我的例子中,当我在安装了cors依赖项后使用app.use(cors)时,我的应用程序冻结并出现网络连接错误,所以我只是添加了上面的代码,没有任何依赖项,它对我来说工作得很好。

wsewodh2

wsewodh22#

可以像这样将选项传递给core函数:

const corsOpts = {
  origin: '*',

  methods: [
    'GET',
    'POST',
  ],

  allowedHeaders: [
    'Content-Type',
  ],
};

app.use(cors(corsOpts));
cyej8jka

cyej8jka3#

我刚刚偶然发现了同样的问题,上面的答案没有帮助。在进一步阅读和测试没有添加CORS头的问题时,我得出结论,app.use()调用的顺序很重要。
因此,如果需要全球CORS设置,请确保调用:app.use(cors(corsOption)),然后使用app.use('/myroute', myRoute);将路线添加到应用程序。

kgsdhlau

kgsdhlau4#

app.use((req, res, next) => {
  //allow access from every, elminate CORS
  res.setHeader('Access-Control-Allow-Origin','*');
  res.removeHeader('x-powered-by');
  //set the allowed HTTP methods to be requested
  res.setHeader('Access-Control-Allow-Methods','POST');
  //headers clients can use in their requests
  res.setHeader('Access-Control-Allow-Headers','Content-Type');
  //allow request to continue and be handled by routes
  next();
});
zpjtge22

zpjtge225#

简单的回答,只需添加:

var cors = require("cors");
app.use(cors());
tktrz96b

tktrz96b6#

更安全的实施

app.use((req, res, next) => {
  //allow access to current url. work for https as well
  res.setHeader('Access-Control-Allow-Origin',req.header('Origin'));
  res.removeHeader('x-powered-by');
  //allow access to current method
  res.setHeader('Access-Control-Allow-Methods',req.method);
  res.setHeader('Access-Control-Allow-Headers','Content-Type');
  next();
})

相关问题