简体   繁体   English

Express JS不发送JSON来响应发布请求

[英]Express JS not sending JSON in response to post request

I'm writing a little AngularJS app that's communicating with an ExpressJS backend for JSON. 我正在编写一个与JSON的ExpressJS后端通信的AngularJS应用程序。 My server.js file looks like: 我的server.js文件如下所示:

var express = require('express'),
    app = express();

//Express 4
app.use(express.static(__dirname, '/'));

app.get('/questions', function(req, res) {
    res.json(questions);
});

app.post('/new_question', function(req, res){
    res.json(req.body);
    //questions.unshift(req.body);
});

app.listen(8080);

When I: curl -H "Content-Type: application/json" -d '{text: "text", votes: 0 }' localhost:8080/new_question I get nothing back. 当我: curl -H "Content-Type: application/json" -d '{text: "text", votes: 0 }' localhost:8080/new_question我什么也没回来。 What am I missing here? 我在这里想念什么? I feel like it must be something exceptionally dumb. 我觉得这一定是非常愚蠢的事情。

Your POST will need a bodyparser middleware as pointed out in comments. 如注释中所指出的,您的POST将需要一个bodyparser中间件。

However, I don't see what's wrong in your GET . 但是,我看不出您的GET有什么问题。 Maybe questions is no valid json? 也许问题是没有有效的json? try simply 简单尝试

res.send(questions,200);

And see what happen. 看看会发生什么。

Also, use a logger to get more infos about your problem : which request status do you get? 另外,使用记录器获取有关您的问题的更多信息:您得到哪个请求状态? etc... 等等...

app.use(express.logger());

place it after your static call if you don't wanna log static content requests. 如果您不想记录静态内容请求,请将其放在静态调用之后。

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

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