Satya Narayana
Satya Narayana

Reputation: 452

Issue with CORS while trying POST request

I am trying to send a post request from my angularJS application which is running on 4200 port as follows to the nodeJS application running on different port 3000.

AngularJS 2.0 Code:

addNewItem(body:string) {
    const headers = new Headers();
    headers.append('Content-Type','application/json');
    return this.http.post('http://10.244.1.59:3000/newBinDevice',body,{
      headers: headers
    })
    .map((response : Response) => response.json());
  }

NodeJS code

var express = require('express');

    module.exports = function(app){
        var db = require('./dbclient');
        var bodyParser = require('body-parser');
        app.use(bodyParser.json());
        app.use(bodyParser.urlencoded({extended:true}));
        db.dbconnection(null,null,null,null,'smartbin',null);
        app.post('/newItem', function(req, res, next) { 
            res.header("Access-Control-Allow-Origin", "*");
            //res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 
            res.header("Access-Control-Allow-Headers", "Content-Type"); 
            res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
            console.log('body request is ' +  req.body + " after stringifying it " + JSON.stringify(req.body) + " array to string " + req.body.toString());
    }

I am getting CORS issue saying that " Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 404." I read somewhere that one cannot send data other than

application/x-www-form-urlencoded
multipart/form-data
text/plain

When I tried to send data as a string instead of JSON object from AngularJS application, i am getting empty data on nodejs application.

Upvotes: 0

Views: 1170

Answers (2)

cartant
cartant

Reputation: 58440

You need to add some more middleware to your express application to support CORS.

You can use the cors package:

var cors = require('cors')
...
app.use(cors());
app.use(bodyParser.json());

That will enable the package's default CORS configuration. The configuration options are outlined in detail in the documentation.

The problem with the code in your question is that you are including the CORS headers in the POST response, but they need to be returned in the pre-flight OPTIONS response. Rather than coding your own CORS implementation, I would suggest using the package mentioned above.

Upvotes: 1

user7461182
user7461182

Reputation:

i am new in stackoverflow, but faced this problem before some time:

use this code in your app.

var cors = require('cors');


app.use(cors({
    'allowedHeaders': ['sessionId', 'Content-Type'],
    'exposedHeaders': ['sessionId'],
    'origin': '*',
    'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
    'preflightContinue': false

}));

And make sure that disable your CORS extension in your browser if any.

Upvotes: 0

Related Questions