0

Having issues getting data back from a http post request to an API I've been building. Throws the error:

XMLHttpRequest cannot load (URL to API here). No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.

Here's the Angular code on the client side:

$http.post('MyAPIsURLHere', {
    date: $scope.information.PubDate
})
.then(console.log)
.catch(console.error);

And here's the Node server side code for my API:

app.post('/getThing', (req, res) => {
    const date = req.body.date;
    const query = Overquery
    const query2 = "alter session set nls_date_format = 'MM/dd/yyyy'";

    oracleDB.execute(query2, (err, result) => {
        if(err) {
            console.error(err);
        }
        else {
            console.log(result);
        }
    });
    oracleDB.execute(query, (err, result) => {
        if(err) {
            console.error(err);
        }
        else {
            res.header('Access-Control-Allow-Origin', '*');
            res.header('Access-Control-Allow-Methods', 'POST');
            res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');

            res.json(result.rows);
        }
    });
});

First time building an API so any suggestions and help would be greatly appreciated!

NoxFly
  • 179
  • 1
  • 12
MattA
  • 255
  • 1
  • 3
  • 10
  • You're properly setting cors headers for the POST request, however, you're likely not properly responding to the OPTIONS request that comes before the post request in some cases. – Kevin B Aug 26 '15 at 21:56

2 Answers2

1

Run the following in your project from a bash shell:

npm install cors --save

It will install this: https://github.com/expressjs/cors

Then add this to your server when creating the app.

var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());

Edit: This will enable CORS for every domain wich is not recomended for security reasons. Check here for further CORS configuration: https://github.com/expressjs/cors#configuring-cors

rahuL islam
  • 510
  • 4
  • 6
Alfonso Presa
  • 1,024
  • 7
  • 11
0

In your node application, this sample of code should solve your issues:

// Allowing X-domain request
var allowCrossDomain = function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Cache-Control");

    // intercept OPTIONS method
    if ('OPTIONS' == req.method) {
      res.send(200);
    }
    else {
      next();
    }
};
app.use(allowCrossDomain);
schankam
  • 10,778
  • 2
  • 15
  • 26