【问题标题】:Uncaught SyntaxError: Unexpected token < for GET requests in production modeUncaught SyntaxError: Unexpected token < for GET requests in production mode
【发布时间】:2019-02-19 06:53:04
【问题描述】:

我已经在 Heroku 中部署了我的程序(Node 后端和 React for frontend by create-react-app)。它适用于 POST 请求,但对于我收到的 GET 请求

Uncaught SyntaxError: Unexpected token

我在 app.js 中有这段代码,用于前端文件夹中构建文件夹的绝对路径:

let root = path.join(__dirname, 'front-end', 'build'); // (on Heroku ==>  
path.join(__dirname, 'front-end', 'build'); )
app.use(express.static(root));
app.use(function(req, res, next) {
  if (req.method === 'GET' && req.accepts('html') && !req.is('json') &&!req.path.includes('.')) {
      res.sendFile('index.html', { root });
   } else next();
 });

我怎样才能修复这部分也适用于 GET 请求?

提前感谢您的帮助。

【问题讨论】:

  • 这可能是因为您收到了针对您的一个请求的 HTML 响应。检查开发人员工具中的网络选项卡。您的 GET 请求可能会收到 HTML 响应。
  • @sudobangbang 是的,我正在构建文件夹中接收 HTML 文件,因为我已经指出它是单页应用程序(至于单页应用程序结构,当 URL 为第一次调用,必须先加载整个页面布局。)我只是想知道如何解决它?

标签: node.js heroku routing create-react-app production


【解决方案1】:

我找到了我的答案,将标题添加到前端的获取请求中,因为在这里我正在检查

req.method === 'GET'

所以我在请求中添加了标头:

fetch('/alladmins', { 
     headers: {"Content-Type": "application/json",
                "Accept" : "application/json"}
      })
    .then(data => data.json())
    .then((data) => { this.setState({ arrayOfAdmins: data });
  }
  , 
  function (error) {
    console.error("Error with fetching /alladmins url:", error);
  });

现在它正在工作,有点奇怪,因为 GET 不应该需要这个标题,但它正在工作。

【讨论】:

    猜你喜欢
    • 2018-01-07
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    相关资源
    最近更新 更多