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

查看:85
本文介绍了Uncaught (in promise) SyntaxError: Unexpected token <在位置 0 的 JSON 中,同时访问节点服务器中的静态文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发小应用程序,使用 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 提供服务,但它也将提供所有其他资产,例如图像、

相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆