如何在快递中为json响应设置路由?

时间:2015-04-26 17:08:50

标签: javascript json angularjs node.js express

我正在尝试按照this Angular tutorial来处理带有承诺的表单提交。我在节点上运行我的服务器,我使用快递处理路由。提交表单后我就到了

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

我的应用程序通过尝试查找response.json的路由进行响应,然后重定向到404页面。然后我得到一个未捕获的语法错误,因为它试图将我的jade模板解析为response.json。

解决此问题的最佳方法是为json响应定义路由吗?或者还有其他我想念的东西?

1 个答案:

答案 0 :(得分:1)

将JSON数据发送到您的服务器只是在特定路径上的正常请求,其中数据作为JSON发送。如果请求是GET,则数据是URL编码的。如果请求是POST,则数据被编码发送到正文中。在任何一种情况下,body-parser模块都会为你解析它。

以下是"/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);

使用body-parser模块有几种不同的方法。您可以在此处查看其他几个示例:How do I consume the JSON POST data in an Express application

而且,客户端代码将是:

var $promise = $http.jsonp('/response.json', config)
相关问题