简体   繁体   English

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

[英]How do I set a route for a json response in express?

I am trying to follow this Angular tutorial for handling form submissions with promises. 我正在尝试遵循此Angular教程来处理带有承诺的表单提交。 I am running my server on node and I'm using express to handle routes. 我正在节点上运行服务器,并且正在使用Express处理路由。 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. 我的应用程序通过尝试找到response.json的路由来进行响应,然后重定向到404页面。 I then get an Uncaught syntax error because it's trying to parse my jade template as the response.json. 然后,我收到了Uncaught语法错误,因为它试图将我的Jade模板解析为response.json。

Is the best way to resolve this to define a route for the json response? 解决此问题的最佳方法是为json响应定义路由吗? Or is there something else I'm missing? 还是我还缺少其他东西?

Sending JSON data to your server is just a normal request on a particular path with the data sent as JSON. 将JSON数据发送到您的服务器只是在特定路径上的常规请求,数据以JSON形式发送。 If the request is a GET, then the data is URL encoded. 如果请求是GET,则对数据进行URL编码。 If the request is a POST, then the data is sent encoded into the body. 如果请求是POST,则将数据编码发送到正文中。 In either case, the body-parser module will parse it for you. 无论哪种情况,body-parser模块都会为您解析。

Here's a simple example for a get request to "/response.json" : 这是获取对"/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. 有多种使用body-parser模块的方法。 You can see several other examples here: How do I consume the JSON POST data in an Express application . 您可以在此处看到其他几个示例: 如何在Express应用程序中使用JSON POST数据


And, the client code would be: 并且,客户端代码将是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM