快速路由/index.js在我的React应用程序中不起作用 [英] Express route /index.js not working in my React app

查看:403
本文介绍了快速路由/index.js在我的React应用程序中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Express中的index.js提取我的React应用程序中的json对象,但是当它加载时,我会收到未处理的拒绝(SyntaxError):JSON中位置0处的意外令牌P".

I'm trying to fetch a json object in my React app from index.js in Express, but when it loads I get "Unhandled Rejection (SyntaxError): Unexpected token P in JSON at position 0".

使用/users.js作为路由时,我成功获取了

I fetched successfully when I used /users.js as the route.

(index.js)

var express = require('express');
var router = express.Router();

 router.get('/', function(req, res, next) {
   vitamins: [
     {
        name: "Vitamin B2"
     }
   ],
   minerals: [
     {
        name: "Zinc"
     }
   ]});
 });


 (React app)

  componentDidMount() {
   fetch('/index')
     .then(res => res.json())
     .then(micros => {
     this.setState({
       micros: micros.vitamins
     });
   })
  }

同样,当我使用相同的代码从/users.js获取时,它也能正常工作.相反,我只是做了fetch('/users').我也尝试过仅执行fetch('/'),但是我只是得到在位置0的JSON中出现意外令牌<".

Again, it worked fine when I fetched from /users.js using the same code. Instead I just did fetch('/users'). I also tried just doing fetch('/'), but I just get "Unexpected token < in JSON at position 0".

推荐答案

错误,意外令牌< JSON在位置0出现的原因是您的响应实际上不是json,而是HTML,类似于404 html响应或500响应. 建议不要使用"/"直接进行服务器调用.这主要是用于加载通常返回HTML的整个应用程序. 您应该为端点维护单独的映射,就像您提到的用户"一样,然后从React fetch调用它. 当您第一次获得响应时,放置一些其他控制台日志或进行调试,您将能够找出服务器正在返回的实际响应

The error, Unexpected token < in JSON at position 0 is coming due to the fact that your response is not really a json but a HTML, something like a 404 html response or a 500 response. It is recommended to not make a direct server call with '/'. This is mainly for loading the entire application which usually returns an HTML. You should maintain separate mapping for end points like you mentioned 'users' and then call it from React fetch. Put some additional console logs or debug when you first get the response and you will be able to figure out the actual response that is being returned by server

这篇关于快速路由/index.js在我的React应用程序中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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