gpt4 book ai didi

javascript - 未捕获的语法错误 : Unexpected token (First program)

转载 作者:行者123 更新时间:2023-12-01 01:18:54 24 4
gpt4 key购买 nike

未捕获的语法错误:意外的标记 <使用 console.log 调用 javascript ("hello world");

我正在 Node 中编写我的第一步,一开始没有任何框架来了解 Node.js 的主要和简单方面

我刚刚在 Node.js (main.js) 中创建了我的服务器并调用了一个index.html,这个index.html调用了一个sayHi.js,它只有一个控制台日志。但这个脚本不起作用...

我想对此 HTML 文件执行 Controller /脚本以开始编程...

//main.js
var http = require("http");
var fs = require("fs");
var url = require('url');

//create a server object:
http.createServer(function(req, res) {

if (req.url === "/index" || req.url === '/') {
fs.readFile('app/views/index.html', function(err, data) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
console.log("Requested URL is index: " + req.url);
res.write(data);
res.end();
});
} else if (req.url === "/modbus") {
fs.readFile('app/views/modbus.html', function(err, data) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
console.log("Requested URL is index: " + req.url);
res.write(data);
res.end();
});

} else {
fs.readFile('app/views/404.html', function(err, data) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
console.log("Requested URL is index: " + req.url);
res.write(data);
res.end();
});
}
})
.listen(8080); //the server object listens on port 8080
console.log('Server running at http://127.0.0.1:8080');
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../scripts/sayHi.js"></script>
<!-- <link rel="stylesheet" href="/app/styles/myStyle.css" /> -->
</head>

<body>
<h1>Hello! Now you know how to serve HTML files using Node.js!!!</h1>

<p id="demo"></p>
<a href="\modbus">Modbus</a>
</body>

</script>
</html>
//sayHi.js
console.log("hello world");

Uncaught SyntaxError: Unexpected token <

最佳答案

我要指出的第一件事是,您的 HTML 文件正在从 ../scripts/sayHi.js 路径寻找名为 sayHi.js 的 javascript 文件。

您的 Html 文件位于 http://localhost:8080/并尝试获取 http://localhost:8080/scripts/sayHi.js您没有路由,因此 server.js 将尝试发送错误 html,该错误位于 404.html 文件中。

这是一个 HTML 文件,但作为 JavaScript 文件注入(inject),这将导致浏览器中的控制台错误。

我的建议是在 header 中返回适当的状态代码,即 404,并在服务器文件中构建到 sayHi.js 的路由。

关于javascript - 未捕获的语法错误 : Unexpected token (First program),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54446914/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com