Uncaught (in promise) SyntaxError: Unexpected token <在位置 0 的 JSON 中,同时访问节点服务器中的静态文件 [英] Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 while acess static files in node server
问题描述
我正在开发小应用程序,使用 react create app with node in thatis application 我想访问 node 中的静态文件,我像这样使用
Hi i am developing small application using react create app with node in thatis application i want to acess static file in node i use like this
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, "/", 'build', 'index.html'));
});
但我收到错误
Uncaught (in promise) SyntaxError: Unexpected token <在 JSON 中的位置 0
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
推荐答案
这是因为您为每个请求提供相同的文件 - 也为原始 HTML 页面所需的脚本提供服务.浏览器请求脚本,它获取 HTML 并且解析器在
或 的
<
上失败.
This is because you are serving the same file for every request - also for the scripts required by the original HTML page. The browser request script, it gets HTML and the parser fails on <
of <doctype>
or <html>
.
您可以在浏览器开发者控制台的网络"选项卡中看到浏览器发出的所有请求 - 我敢打赌,您正在请求类似 script.js
的内容,而不是 JavaScript 内容您将获得 index.html
文件的 HTML 内容.
You can see in the Network tab of your browser's developer console all of the requests that your browser is making - I can bet that you're requesting something like script.js
and instead of JavaScript contents you get the HTML contents of your index.html
file.
您似乎在使用 Express.使用 express.static
代替 res.sendFile()
It seems that you're using Express. Use express.static
to serve static files instead of res.sendFile()
由于您在 build
中似乎拥有每个静态文件,请使用以下内容:
Since it seems that you have every static file in build
, use something like this:
const path = require('path');
const express = require('express');
const app = express();
const dir = path.join(__dirname, 'build');
app.use(express.static(dir));
app.listen(3000, function () {
console.log('Listening on http://localhost:3000/');
});
这是您需要的整个程序.当然,您可以更改端口号.
This is the entire program that you need. Of course you can change the port number.
它将正确地为您的 index.html
提供服务,但它也将提供所有其他资产,例如图像、 所需的客户端脚本、CSS文件等,以及其他 HTML 文件(如果有).
It will serve your index.html
correctly but it will also serve all of the other assets like images, client-side scripts required with <script>
, CSS files etc. plus also other HTML files if there are any.
如果您不想使用 Express,请参阅此答案以获取更多提供文件的选项:
If you don't want to use Express then see this answer for more options of serving files:
这篇关于Uncaught (in promise) SyntaxError: Unexpected token <在位置 0 的 JSON 中,同时访问节点服务器中的静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!