sublime text代码编辑器界面里有两个文件,一个是app.js,另一个是form.html:
其中,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里的代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method="post" action="http://localhost:3000">
<input type="submit" name="">
</form>
</body>
</html>
网站服务器已启动成功,显示如下:
网上的教程展示req.url的三个步骤里提到
第一步:在chrome浏览器地址栏里输入localhost:3000后回车,会显示not found:
第二步:在sublime text代码编辑器里的form.html处右键选择open in browser,浏览器弹出界面后点击提交按钮,会显示not found:
第三步:在显示not found界面上的地址栏里输入localhost:3000/index或localhost:3000/list,会显示welcome to homepage或welcome to listpage:
然而,按照网上教的步骤去做的话,第一步可以做到教程所说的效果,即在chrome浏览器地址栏里输入localhost:3000后回车,显示not found:
但第二步和第三步就做不到所说的效果。
如第二步,在sublime text代码编辑器里的form.html处右键选择open in browser,浏览器弹出界面后点击提交按钮,显示无法访问此网站,而没有显示not found:
如第三步,在此无法访问此网站界面上的地址栏里输入localhost:3000/index和localhost:3000/list,均显示无法访问此网站,而没有显示welcome to homepage或welcome to listpage:
经过一番摸索,发现只要在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 保存这个动作,实在是非常麻烦!
请问其中的原因是什么?如何解决?恳请展示解决此问题的每一个步骤,谢谢