react使用两种方式解决跨域

一、 请求免费天气api接口(https://j.i8tq.com/weather2020/weatherMap/wyJsonList.js)

1、在componentDidMount函数里面发送fetch请求
  componentDidMount() {
     fetch('https://j.i8tq.com/weather2020/weatherMap/wyJsonList.js',{
      method:'GET',
      headers:{
        'Content-Type':'application/json;charset=UTF-8'
      },
    })
     .then(res =>res.json())
     .then((data) => {
       console.log(data)  
     }) 
  }
2、报错信息
  Access to fetch at 'https://j.i8tq.com/weather2020/weatherMap/wyJsonList.js' from origin 'http://localhost:3000' has been blocked by CORS policy: 
  Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 
  If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
  index.js:19 GET https://j.i8tq.com/weather2020/weatherMap/wyJsonList.js net::ERR_FAILE
  localhost/:1 Uncaught (in promise) TypeError: Failed to fetch

在这里插入图片描述

二、react跨域解决方案之一(仅在开发模式下生效)

1、执行npm run eject暴露配置文件
2、找到webpackDevServer.config.js文件,添加配置(104行)
  proxy: {
    	'/api': {
            target: 'https://j.i8tq.com/weather2020/weatherMap', // 后台服务地址以及端口号
            ws: true,
            changeOrigin: true, //是否跨域
            pathRewrite: { '^/api': '' }
          }
     },
3、使用fetch访问接口地址
 componentDidMount() {
        fetch('/api/wyJsonList.js',{
        method:'GET',
        headers:{
            'Content-Type':'application/json;charset=UTF-8'
        },
        })
        .then(res =>res.json())
        .then((data) => {
        console.log(data)  
        }) 
    }

三、react跨域解决方案之二

1、.安装http-proxy-middleware
npm install http-proxy-middleware --save
2、在src目录下面新建文件:setupProxy.js

文件内容如下
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function (app) {
    app.use(createProxyMiddleware('/api',
        {
            "target": "https://j.i8tq.com/weather2020/weatherMap",
            "changeOrigin": true,
            "pathRewrite": {
                "^/api": "/"
            }
        }))
}
3、使用fetch访问接口地址
 componentDidMount() {
        fetch('/api/wyJsonList.js',{
        method:'GET',
        headers:{
            'Content-Type':'application/json;charset=UTF-8'
        },
        })
        .then(res =>res.json())
        .then((data) => {
        console.log(data)  
        }) 
    }

成功数据

react使用两种方式解决跨域_第1张图片

你可能感兴趣的:(reactjs)