首页 > 解决方案 > 节点服务器自行重启

问题描述

所以我有这个文件“client.html”,它将一个字符串发送到节点服务器

客户端.html

<!DOCTYPE html>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="http://127.0.0.1:3000/search" method='get'>
        <input type="text" name="name">
        <input type="submit" value="search">
    </form>
</body>
</html>

服务器获取输入字符串并在控制台上打印出来。一段时间后,它应该打印“其他东西”。

index.js

var express = require('express');

var app = express();

var bodyParser = require('body-parser');
var util = require('util');

var port = process.env.PORT || 3000;

app.all('/', function(req, res) {
    res.sendFile(__dirname+'/client.html');
}); 

app.get('/search', function(req, res) {
    var name = req.query.name;
    console.log(name);
    setTimeout(function(){
        console.log("Something else");
    }, 240000);
}) ;

//listen in a specific port
app.listen(port);

//check status
console.log('Server running at http://localhost:' + port); 

相反,“name”变量被打印出来,然后过了一段时间,在打印出“其他东西”之前,“name”变量再次被打印出来,就好像有人点击了表单中的发送按钮一样客户。需要一些帮助来解决这个问题

标签: javascriptnode.js

解决方案


我想您应该在连接超时并且浏览器尝试重新连接之前回复客户端:

 app.get('/search', function(req, res) {
   var name = req.query.name;
   console.log(name);
   setTimeout(function(){
    console.log("Something else");
   }, 240000);

   res.end("Searching ...");
}) ;

推荐阅读