0

I am trying to follow this Angular tutorial for handling form submissions with promises. I am running my server on node and I'm using express to handle routes. When the form is submitted and I get to the line

var $promise = $http.jsonp('response.json', config)

My application responds by trying to find a route for response.json and then redirects to a 404 page. I then get an Uncaught syntax error because it's trying to parse my jade template as the response.json.

Is the best way to resolve this to define a route for the json response? Or is there something else I'm missing?

DJ_Beardsquirt
  • 279
  • 4
  • 14
  • 1
    You will need a specific route on the server for `response.json` so you can write code to handle that JSON that is being sent to the server. That's where you're sending the request to so the server needs a handler for it. – jfriend00 Apr 26 '15 at 17:21
  • Thanks, this helps a lot. But I'm having a hard time finding an example to look at of an express route handling a json response. Can you suggest where I could find one? – DJ_Beardsquirt Apr 26 '15 at 20:42

1 Answers1

2

Sending JSON data to your server is just a normal request on a particular path with the data sent as JSON. If the request is a GET, then the data is URL encoded. If the request is a POST, then the data is sent encoded into the body. In either case, the body-parser module will parse it for you.

Here's a simple example for a get request to "/response.json":

var express = require("express");
var app = express();
var bodyParser = require('body-parser');

app.get('/response.json', bodyParser.json(), function (req, res) {
  if (!req.body) return res.sendStatus(400);
  // req.body is the parsed JSON that was sent with this request
  // process it here
});

app.listen(80);

There are several different ways to use the body-parser module. You can see several other examples here: How do I consume the JSON POST data in an Express application.


And, the client code would be:

var $promise = $http.jsonp('/response.json', config)
Community
  • 1
  • 1
jfriend00
  • 580,699
  • 78
  • 809
  • 825