0

I am learning Angular and Node and I am trying to figure out how to have my Angular app hit a separate app hosting a rest API.

The request body is displayed as { '{"name":"test"}': '' } and I expect it to be displayed as { "name" : "test"}

This is the front-end app that sends the post request.

$http({
  method: 'POST',
  url: 'http://localhost:8080/api/test',
  data: {
    "name": 'test'
  },
  dataType: "json",
  headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});

It is hitting the route defined as

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.all('/', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
 });
router.post('/test', function(req, res) {
    var name = req.body.name;
    console.log(req.body);
});

I expect the issue to be with the content-type being application/x-www-form-urlencoded but I cannot figure out how to allow cors with application/json.

dberry2002
  • 3
  • 1
  • 2

1 Answers1

0

JSONP can be used for performing CORS requests (more about json/jsonp here What are the differences between JSON and JSONP?), and in AngularJS documentation - jsonp using $http

Community
  • 1
  • 1
shershen
  • 9,875
  • 11
  • 39
  • 60
  • Thanks for the reply! That worked as well. I read a little more about CORS and discovered the concept of pre-flighting and I added a function that would send a 200 reply to an application/json request and the above code works now. – dberry2002 Jan 20 '15 at 20:32
  • Will do whenever the 4 minute timer is up. Thanks again :) – dberry2002 Jan 20 '15 at 20:33