javascript - 怎么解决fetch的跨域问题?现在在用react-router做一个SPA

查看:165
本文介绍了javascript - 怎么解决fetch的跨域问题?现在在用react-router做一个SPA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

现在在用react-router做一个SPA应用,也存在跨域问题,但是我在网上看见别人有的web页面可以请求到,是不是别人自己用服务器做处理了?

项目地址

fetch(getLatestNews(),{
          method: 'GET',
          mode: 'cors',
      })
      .then((response) => {
          console.log(response)
        if (response.ok) {
          return response.json()
        }
      })
      .then((responseData) => {
          
        this.setState({
          isLoaded: true,
        })
      })
      .catch(() => {
        this.setState({
          isLoaded: false,
        })
      });

警告

Fetch API cannot load http://news-at.zhihu.com/api/... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.xboxyan.com' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

解决方案

推荐两种方案
1.后台启用cors跨域资源共享 CORS 详解

2.使用代理nginx conf文件里配置proxy路径或者使用npm的包http-proxy-middleware

这篇关于javascript - 怎么解决fetch的跨域问题?现在在用react-router做一个SPA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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