14

I am using Node as backend server and Angular 4 as frontend. I am trying to send the result of query through soap protocol. The function works fine but with CORS PLUGIN installed in the browser.But how can I solve it without those plugins.

I have searched for some solutions and I have installed CORS package in my node file and also did the following things to my server.js file.

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

But it didn't help. The error is still there.How can I solve this error.I have posted my server side code following:

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

Error

enter image description here

cantona_7
  • 1,127
  • 4
  • 21
  • 40
  • whats is the error can you please post the error ? – Richard Elite Feb 28 '18 at 14:26
  • this might be helpful https://stackoverflow.com/questions/7067966/how-to-allow-cors?rq=1 – Richard Elite Feb 28 '18 at 14:29
  • @ManojKrishna I have posted the screenshot of the error – cantona_7 Feb 28 '18 at 14:29
  • @ManojKrishna I have used those headers in my code..,but still the error presists – cantona_7 Feb 28 '18 at 14:31
  • 1
    Try adding `app.options('*', cors());` to your node code. That makes it handle the preflight OPTIONS request. See the answers at https://stackoverflow.com/questions/48133339/make-cors-request-with-polymer-iron-ajax-and-node-js/48133489#48133489 and https://stackoverflow.com/questions/42323139/angular2-application-call-node-js-function/42323229#42323229 – sideshowbarker Feb 28 '18 at 22:33
  • @sideshowbarker yes I have added that..,but still the same error..,should I declare it inside the function or just at the header – cantona_7 Mar 01 '18 at 08:56

6 Answers6

19

It may be late but I hope it would help someone. For me I solved the CORS policy in node.js by just adding the following piece of code:

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

In my case when I used app.use(cors) after I installed the cors dependency, my app just froze and got a network connection error so I just added the code above without any dependencies and it worked well for me.

zahra shahrouzi
  • 862
  • 7
  • 18
Sparks
  • 496
  • 7
  • 16
17

You can pass an options to the core function like this :

const corsOpts = {
  origin: '*',

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

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

app.use(cors(corsOpts));
user7364588
  • 1,014
  • 2
  • 12
  • 32
3

I have just stumbled upon the same issue and the answers above did not help. While further reading and testing the issue of CORS headers not being added I have concluded that the order of app.use() calls matter.

So make sure that if you want a global CORS setting you call:app.use(cors(corsOption)) BEFORE adding the routes to the app with app.use('/myroute', myRoute);.

Teodor
  • 296
  • 1
  • 6
1

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();
});
rahulyadav
  • 73
  • 2
1

For simple answer, just add:

var cors = require("cors");
app.use(cors());
ouflak
  • 2,458
  • 10
  • 44
  • 49
-1

More secure implementation

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();
})
skvp
  • 1,940
  • 1
  • 20
  • 25