0

I am trying restful web service in angular with node express as a server. I am facing Access-Control-Allow-Origin. My express code follows

var express = require('express');
var app = express();

app.get('/getdata',function (req,res){
    console.log("serving request from here");
    res.header("Access-Control-Allow-Origin", "*");
    res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify({ records: {name: 'raj', country: 'india'} }));
});
app.get('/postdata', function(req, res){
    console.log("requested value dddd");
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
    console.log("request value :::",req);
    res.send(JSON.stringify({status: 'Success1111'}));
});

var server = app.listen('4050',function(){
    console.log("server running");
    var host = 'localhost';
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});

I am handling the post request from angular app in /postdata route in the above code.

My angular sample code

<script src="angular.js"></script><!-- load angular -->
<div ng-app="myApp" ng-controller="customersCtrl"> 
<ul>
    {{ values.name + ', ' + values.country }}
    {{ mystatus }}
</ul>
</div>
<script>
var app = angular.module('myApp', []);
var url = "http://localhost:4050";
app.controller('customersCtrl', function($scope, $http) {
// Simple GET request example:
$http({
  method: 'GET',
  url: url+'/getdata'
}).then(function successCallback(response) {
    console.log("myres ::",response);
    $scope.values = response.data.records;
  }, function errorCallback(response) {
  });

// $http.defaults.headers.post = {
//         'Access-Control-Allow-Origin': '*',
//         'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
//         'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With'
//         };
//         $http.defaults.useXDomain = true;
    $http({
  method: 'POST',
  url: url+'/postdata',
 data: { test: 'test' }
}).then(function successCallback(response) {
    console.log("response from heree",response);
    $scope.mystatus = response.data.records;
  }, function errorCallback(response) {
    console.log("error");
  });
});
</script>

At the time of page load i initiate the request,Getdata request working properly, but for the postdata request it shows the following error shows in the console.

XMLHttpRequest cannot load http://localhost:4050/postdata. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. 

But when i open the url in new tab from console error it shows the proper response. I face a difficulty here why the request shows error. Could anyone help on this. Thanks in advance

Rajan
  • 416
  • 1
  • 7
  • 25

1 Answers1

0

Since your POSTed data content-type is 'application/json', browser will do a pre-flight OPTIONS request. So you need to respond with appropriate Access-Control headers in the OPTIONS call response.

I have been able to get around the error by adding the options method. Also I corrected to app.post('/postdata',...)

app.options('/postdata', function(req, res){
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.send(200);
});

app.post('/postdata', function(req, res){
    console.log("requested value dddd");
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
    console.log("request value :::",req);
    res.send(JSON.stringify({status: 'Success1111'}));
});

If you don't explicitly define the options method, then express framework simply responds with 200OK without the access control headers. I'm not a node.js expert, so there could be better ways to code this.

In this SO post they have discussed how to handle this as a middleware.

You can also use the cors package - https://www.npmjs.com/package/cors

Community
  • 1
  • 1
Vishal John
  • 4,231
  • 25
  • 41