【问题标题】:Request a data to Backend by using Fetch 'Get' (with this error message Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0)使用 Fetch 'Get' 向后端请求数据(带有此错误消息 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0)
【发布时间】:2021-11-10 14:30:34
【问题描述】:

几周前我刚刚开始学习 React,我尝试制作一个 Nike 网站进行练习。当我使用 fetch 向后端请求数据时

p.s)(带有此错误消息 Uncaught (in promise) SyntaxError: Unexpected token

componentDidMount() {
    fetch(`${API}${this.props.location.pathname}`)
      .then(res => res.json())
      .then(data => {
        console.log(data);
        this.setState({
          productsInfo: data.result,
        });
      });
    console.log('apiCheck', API);
  }

我期望的请求 URL 是“http://10.58.6.96:8000/products”。但是,requestURL 是“http://localhost:3000/10.58.6.96:8000/products”,其中包括我的本地地址。当我 console.log API 时,它也显示 10.58.6.96:8000。你能帮我解决这个问题吗?如果您需要我的整个代码,请告诉我!非常感谢您的帮助!

【问题讨论】:

  • 你在控制台上得到的API 的值是多少?你想打什么 api GET
  • 你能在提到 API 的地方分享你的代码
  • fetch('//${API}${this.props.location.pathname}') 前面加上两个斜杠必须做到这一点
  • @AshishKamble 我的 api 是 10.58.6.96:8000 所以当我将 url 获取到后端时,我会得到我想要的数据!
  • @AshishKamble API 只是 export const API = '10.58.6.96:8000';在 config.js 文件中,我将其导入 main.js!

标签: reactjs


【解决方案1】:

添加两个斜线就可以了

fetch(`//${API}${this.props.location.pathname}`)

【讨论】:

  • 当我将 ` 更改为 ' 时,错误消息显示 [TypeError: Failed to fetch] 和 500 错误 .. :(
  • 10.58.6.96:8000/products 不存在?,${API}${this.props.location.pathname} 的 console.log 输出什么?
  • 当我写 fetch(//${API}${this.props.location.pathname}) 你说的。 200 这意味着效果也很好,但产品没有出现。但是,当我输入“10.58.6.96:8000/products”时,效果很好!我不确定哪一部分出了问题
  • 当我 console.log ${API}${this.props.location.pathname} 时,它显示 10.58.6.96:8000/products 很好!
  • 那么,您的10.58.6.96:8000/products 接受跨域吗?是本地地址吗?限制在某些 ip 上?因为 url 对我不起作用
【解决方案2】:

将配置中API 的值更改为http://10.58.6.96:8000 而不是10.58.6.96:8000。如果协议不存在 (http),则 fetch 将假定它是相对路径。

【讨论】:

  • 感谢您的帮助!但我不需要添加 https,因为如果我添加这个并且当我尝试 console.log 地址时,console.log 显示两个 https
  • 所以你得到http://localhost:3000/http://10.58.6.96:8000/products?
猜你喜欢
  • 2017-12-15
  • 2021-03-02
  • 2020-03-26
  • 2019-08-14
  • 2020-10-10
  • 1970-01-01
  • 1970-01-01
  • 2021-02-15
相关资源
最近更新 更多