POST 到 Node.js 服务器导致长时间加载,从而导致 ERR_EMPTY_RESPONSE

mai*_*n.m 1 html javascript forms post node.js

我有一个简单的表单,将用户输入发布到服务器。提交表单后,页面加载时间较长,导致 ERR_EMPTY_RESPONSE。但是,我可以console.log很好地从表单中输入内容来验证表单确实已发布到服务器。

这是我正在处理的内容:

<form method="post" action="/">
    <input type="text" name="userZipcode" placeholder="Enter your zip code">
    <button type="submit">ENTER</button>
</form>
Run Code Online (Sandbox Code Playgroud)

app.use(bodyParser.urlencoded({
    extended: false
}));

app.use(bodyParser.json());

app.get('/', (req, res, next) => {
    fetch(url)
    .then(res => res.json())
    .then(data => res.render('pages/index'))
    .catch(err => {
        console.log(err);
        res.sendStatus(500);
    });
});

app.post('/', function(req, res) {
    let zipcode = req.body.userZipcode;
    console.log('Your location is: ' + zipcode);
});
Run Code Online (Sandbox Code Playgroud)

注意:获取请求最终会将数据从 API 响应传递到我的 EJS 页面,但目前它除了渲染索引页面之外什么也不做。

上面的表单有效,我console.log按照预期从终端的输入字段中获得了一个带有邮政编码的信息。但是,此后页面只会加载,直到出现上述错误为止。我知道我错过了一些重要的东西,但我不知道那是什么!

Wes*_*gur 5

在您的 POST 路由中,您必须做出响应。您的代码没有响应请求。这会导致 ERR_EMPTY_RESPONSE。

app.post('/', function(req, res) {
    let zipcode = req.body.userZipcode;
    console.log('Your location is: ' + zipcode);
    res.end("your response");
});
Run Code Online (Sandbox Code Playgroud)