【发布时间】:2020-05-26 04:05:13
【问题描述】:
作为一个整体,我对 webdev 还是很陌生,这是我第一次尝试使用 Node.js 设置本地服务器。但问题是我在 test.js 第 1 行中收到“SyntaxError: Unexpected token '
这是我的 test.js 文件
console.log('*');
这是我的 index.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>
<h1>Test</h1>
</body>
<script type="text/javascript" src = "test.js"></script>
</html>
这是我使用“node server.js”运行的服务器文件
const http = require('http');
const fs = require('fs');
const port = 3000;
const server = http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
fs.readFile('../index.html', function(error, data) {
if(error) {
res.writeHead(404);
res.writeHead('Error: File Not Found');
} else {
res.write(data);
}
res.end();
})
});
server.listen(port, function(error) {
if(error) {
console.log('something went wrong', error);
} else {
console.log('Server is listenting on port ' + port);
}
});
据我了解,这是最基本的千篇一律的代码,我可以用来测试我的本地服务器、html 文件和 test.js 文件是否都可以很好地协同工作,但显然有些事情正在发生错误的。当我单击控制台中的错误时,它会显示我的 index.html 文件,但它说它是我的 test.js 文件,几乎就像正在读取 html 代替我的 javascript 并且正在对其应用 javascript 错误处理一样。我已经检查了几次路径,我 99.99% 确信它们是正确的。不过,我对此一无所知,请告诉我是否有人遇到过类似的情况。谢谢!
【问题讨论】:
标签: javascript html node.js