node里的req.url,需要每一次都要做保存动作,才能每一次在浏览器里显示想要的内容,否则就显示无法访问此网站?

sublime text代码编辑器界面里有两个文件,一个是app.js,另一个是form.html:

img

其中,app.js里的代码如下:

const http = require('http');
const app = http.createServer();
app.on('request', (req, res) => {
    // console.log(req.method);
    // console.log(req.url);
    if (req.url == '/index') {
        res.end('welcome to homepage');
    } else if (req.url == '/list') {
        res.end('welcome to listpage');
    } else {
        res.end('not found');
    }
    if (req.method == 'GET') {
        res.end('get')
    } else if (req.method == 'POST') {
        res.end('post')
    }
    // res.end('

hello user

'
); }); app.listen(3000); console.log('网站服务器启动成功');

form.html里的代码如下:

html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
head>
<body>
    <form method="post" action="http://localhost:3000">
        <input type="submit" name="">
    form>
body>
html>

网站服务器已启动成功,显示如下:

img

网上的教程展示req.url的三个步骤里提到
第一步:在chrome浏览器地址栏里输入localhost:3000后回车,会显示not found:

img

第二步:在sublime text代码编辑器里的form.html处右键选择open in browser,浏览器弹出界面后点击提交按钮,会显示not found:

img

第三步:在显示not found界面上的地址栏里输入localhost:3000/index或localhost:3000/list,会显示welcome to homepage或welcome to listpage:

img

img

然而,按照网上教的步骤去做的话,第一步可以做到教程所说的效果,即在chrome浏览器地址栏里输入localhost:3000后回车,显示not found:

img

但第二步和第三步就做不到所说的效果。
如第二步,在sublime text代码编辑器里的form.html处右键选择open in browser,浏览器弹出界面后点击提交按钮,显示无法访问此网站,而没有显示not found:

img

如第三步,在此无法访问此网站界面上的地址栏里输入localhost:3000/index和localhost:3000/list,均显示无法访问此网站,而没有显示welcome to homepage或welcome to listpage:

img

img

经过一番摸索,发现只要在sublime text代码编辑器里的app.js界面按 ctrl + s 保存后,第二步点击提交后会显示not found,第三步在地址栏里输入localhost:3000/index或localhost:3000/list后会显示welcome to homepage或welcome to listpage,但是,如果想每一次都显示出想要的内容而不显示无法访问此网站的话,就都要每一次在sublime text代码编辑器里的app.js界面做 ctrl + s 保存这个动作,实在是非常麻烦!

请问其中的原因是什么?如何解决?恳请展示解决此问题的每一个步骤,谢谢

这是因为你使用了多次res.end,这个一次请求的逻辑中,只能输出使用一次res.end,使用之后代码请求已经返回结束了,如果你在之后再次调用,程序会报错,直接抛出异常,程序停止运行了,所以你需要每次保存后重新启动。