【问题标题】:React App not resolving fetch route: Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0React App未解析获取路由:未处理的拒绝(SyntaxError):JSON中位置0处的意外令牌<
【发布时间】:2018-02-09 00:22:58
【问题描述】:

我在快速服务器中的获取源 ('wx') 正在返回: 未处理的拒绝 (SyntaxError): 意外的标记 在下面的 fetch 行。 'wx' 的获取源返回 404。(虽然这是为最终的天气服务设置的,但这里的任何测试都返回 404)。

这是反应:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  state = {wx: []}

  componentDidMount() {
    fetch('/wx').then(res => res.json()).then(wx => this.setState({ wx }));
  }

  render() {
    return (
      <div className="App">
        <h1>Weather</h1>
        {this.state.wx.map(weather =>
          <div key={weather.id}>{weather.main}>{weather.description}</div>
        )}
      </div>

    );
  }
}

export default App;

这里是 wx.js 的路由:

var express = require('express');
var app = express();
var router = express.Router();
var request = require('request');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');

    app.get('/', function(req, res){

        request({
                url: 'http://jsonplaceholder.typicode.com', //URL to hit
                method: 'POST'

            }, function(error, response, body){
                if(error) {
                    console.log(error);
                } else {
                    console.log(body);
                }
            });

            res.send(body);
    }); 

    module.exports = router;

为什么会返回 404,我该怎么办?

【问题讨论】:

    标签: javascript json node.js reactjs express


    【解决方案1】:

    听起来你忘记在你的 package.json 中设置你的代理端口,所以它返回 html。我有同样的问题,我只是要在我的 package.json 中设置我的代理:“proxy”:“http://localhost:3001”,

    【讨论】:

    【解决方案2】:

    您的错误与您收到的 404 错误有关。 res.json() 尝试将响应的正文转换为 JSON 对象,但由于响应是 HTML 文档而失败。

    你可以做的是在返回json之前检查响应是否成功。

    fetch('/wx').then(res => {
      if(res.status === 200) return res.json();
      else return { error: 'there was an error with response' }
    }).then(wx => {
      if(wx.error) { /* handle error here */ }
      else {
        this.setState({ wx })
      }
    });
    

    【讨论】:

    • 奇怪...响应应该是直接的 json...但是 html 确实解释了 404。所以是的,必须先在那个地方捕获。谢谢。
    猜你喜欢
    • 2018-10-22
    • 2021-07-01
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 2018-03-18
    • 2022-10-13
    • 2023-03-11
    相关资源
    最近更新 更多