繁体   English   中英

javascript 错误 - “SyntaxError: Unexpected token '<' (anonymous function)”在第一行

[英]javascript error - “SyntaxError: Unexpected token '<' (anonymous function)” in the very first line

作为一个整体,我对 webdev 还是很陌生,这是我第一次尝试使用 Node.js 设置本地服务器。 但问题是我在 test.js 第 1 行中收到“SyntaxError: Unexpected token '<' (anonymous function)”。我知道它实际上不在第 1 行,因为第 1 行没有代码。此外,我的javascript 文件,html 文件和我的服务器 js 文件都是非常基本的,我不知道他们怎么会 go 出错。

这是我的 test.js 文件



console.log('*');

这是我的索引。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 文件是否都可以很好地协同工作,但显然出了点问题。 When I click on the error in the console, it shows my index.html file but says it is my test.js file almost as if the html is being read in place of my javascript and the javascript error handling is being applied to it. 我已经检查了几次路径,我 99.99% 确定它们是正确的。 我对此一无所知,如果你们中的任何人遇到过类似的事情,请告诉我。 谢谢!

【原因描述】
没有处理不同的请求或设置 static 资源。
您服务器中的所有请求都会响应 index.html。

在此处输入图像描述

您可以在 createServer function 中添加控制台日志。 因此,您会发现当 req.url 是 test.js 时,您仍然会返回 ./index.html 给请求。

const server = http.createServer(function (req, res) {
    console.log(req.url)
    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();
    })
});

[改进]
确保在请求 url 包含.js(或其他)时,它将返回正确的响应。

const server = http.createServer(function (req, res) {
    // fs.readFile('../index.html', function(error, data) {
    fs.readFile(__dirname + req.url, function (err,data) {
        if(error) {

https://nodejs.org/en/knowledge/HTTP/servers/how-to-serve-static-files/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM