You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React应用VPS部署后直接访问路由报Uncaught SyntaxError求助

问题:React路由直接访问空白,控制台报Unexpected token '<'错误
  • 部署在VPS的React应用,直接访问http://xx.xxx.xxx.xx/post/22这类路由时页面空白,控制台报错:Uncaught SyntaxError: Unexpected token '<' (at main.19f83932.js:1:1)
  • 从主页点击链接访问相同路由显示正常,本地开发环境(http://localhost:3000/post/22)无此问题
  • 已通过GitHub部署API和客户端,执行npm run build生成构建文件,使用Nginx作为服务器;注册、登录、创建帖子等功能正常,但创建帖子后通过window.location.replace("/post/" + res.data.postid)跳转时,同样出现空白页和上述报错

附public目录下index.html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta name="description" content="Web site created using create-react-app" />
    <link href="https://fonts.googleapis.com/css2family=Josefin+Sans:wght@100;200;300;400;500;600;700&family=Lora:ital,wght@1,400;1,500;1,600&family=Varela&family=Varela+Round&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <style>*{margin: 0;}</style>
    <style>.link{text-decoration: none;color: inherit;}</style>
    <title>A Blog</title>
</head>
<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
</body>
</html>

解决思路

  • 修正Nginx配置:React是单页应用(SPA),直接访问子路由时Nginx找不到对应文件,会返回index.html内容,导致JS文件被解析成HTML引发错误。需修改Nginx配置,将所有路由请求转发到index.html:
    server {
        listen 80;
        server_name xx.xxx.xxx.xx;
    
        root /path/to/your/react/build;
        index index.html;
    
        location / {
            try_files $uri $uri/ /index.html;
        }
    
        # 若有API代理需求,添加对应配置
        location /api {
            proxy_pass http://localhost:your-api-port;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
    }
    
  • 检查资源路径:确认index.html中引用的JS、CSS文件路径为绝对路径。若为相对路径,子路由下会从/post/目录查找资源,导致404后返回index.html引发错误。可在package.json中添加"homepage": "/",重新执行npm run build后部署。
  • 调整路由模式:若不想修改Nginx,可将React Router的browserHistory模式切换为hashHistory模式(路由带#号),但会影响URL美观。

内容的提问来源于stack exchange,提问作者Al.U.Mak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 05:52:51