在代码编辑器界面里显示有app.js和form.html两个文件:
app.js如下:
const http = require('http');
const app = http.createServer();
const url = require('url');
app.on('request', (req, res) => {
// console.log(req.method);
// console.log(req.url);
// console.log(req.headers['accept']);
res.writeHead(200, {
'content-type': 'text/html;charset=utf8',
'hello': 'world'
});
// console.log(req.url);
let { query, pathname } = url.parse(req.url, true).query;
console.log(url.parse(req.url, true).query);
console.log(query.name);
console.log(query.age);
if (pathname == '/index' || pathname == '/') {
res.write('欢迎来到首页
');
} else if (pathname == '/list') {
res.write('welcome to listpage');
} else {
res.write('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>
已成功启动网站服务器:
网上的教程说, 在powershell里,console.log(query.name) 和 console.log(query.age) 会显示出zhangsan和20这两个值:
然而,我按照教程实施出来的效果则如下,显示name未定义,与教程显示的有出入,且chrome浏览器显示无法访问此网站::
请问代码是否有写得不对的地方?如何解决?恳请在现有基础上展示说明
你的代码中有一行:console.log(query.name),但是在请求的url中并没有携带name的数据。因此,显示"name未定义"的错误。你可以对请求的数据进行检查,或者添加默认值以避免这个错误。代码报错:"TypeError: Cannot read properties of undefined (reading 'name')",很有可能是因为没有获取到请求的参数。请检查代码是否正确解析了 URL 中的参数。此外,浏览器显示“无法访问此网站”可能是因为服务器没有正确启动,或者网络链接问题导致服务器无法访问。