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