简体   繁体   English

清空Node.js / Express响应

[英]Empty Node.js/Express response

I have a POST request that I want to process: 我有一个要处理的POST请求:

var app = require('express')();
var bodyParser = require('body-parser');
app.use(bodyParser());
. . .
app.post('/signup', function(req, res) {
    console.log('name: ' + req.body.name);
    console.log('email: ' + req.body.email);
    . . .
});

All seems well and dandy. 一切看起来都很好,很花哨。

My client: 我的客户:

<html><body>
    <form>
    Name:<br>
    <input type="text" name="name"><br>
    Email:<br>
    <input type="text" name="email"><br>
    <input id="submit" type="submit" value="Submit">
    </form>

<script type="text/javascript" src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script>
$('input#submit').click(function() {
    $.ajax({
        url: 'http://localhost:5000/signup',
        type: 'post',
        dataType: 'json',
        data: $('form').serialize(),
        success: function(data) {
            console.log('response:', data);
        }
    });
    return false;
});
</script></body></html>

The problem? 问题? success is never called in the client. 客户从未调用过success Eventually, Chrome JS-debug window shows: net::ERR_EMPTY_RESPONSE . 最终,Chrome JS-debug窗口显示: net::ERR_EMPTY_RESPONSE

I have tried doing res.send(200) , res.send('') and res.end() in the server, but without success. 我已经尝试在服务器中执行res.send(200)res.send('')res.end() ,但没有成功。

My Node.js version is 4.2.6, and I think my Express version is 4.4.1. 我的Node.js版本是4.2.6,我认为我的Express版本是4.4.1。

jQuery Docs jQuery文档

dataType - The type of data that you're expecting back from the server; dataType - 您希望从服务器返回的数据类型;

data - Data to be sent to the server; data - 要发送到服务器的数据;

So, your frontend application expect a valid JSON back, but primaries (string, number, boolean) aren't a valid JSON, they have to be converted. 因此,您的前端应用程序期望返回有效的JSON,但是primaries(字符串,数字,布尔值)不是有效的JSON,它们必须被转换。

In order to perform this on fly: 为了在飞行中执行此操作:

res.json('success');

or 要么

res.status(200).json('success');

If you want to stick with send method, you could write: 如果你想坚持使用send方法,你可以写:

res.send(JSON.stringify('success'));

Also, sometimes this problem is related to ipconfig in windows and network connection 此外,有时这个问题与Windows和网络连接中的ipconfig有关

can you try this, 你能试试吗

$.post('http://localhost:5000/signup', $('form').serialize(), function(data) {
    console.log(data);
});

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

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