current position:Home>Cross domain problem handling of react

Cross domain problem handling of react

2021-08-27 02:06:54 He Xiaoshi

This is my participation 8 The fourth of the yuegengwen challenge 20 God , Check out the activity details :8 Yuegengwen challenge

Suitable for react17+ Version of

First step : stay package.json Inside plus proxy

This proxy Must if String type , And it is a local path that needs to cross domain

"proxy": "http://localhost:3000"
 Copy code 

The second step : Set up setupProxy.js, Set cross domain path settings

stay src below , newly build setupProxy.js, The code is as follows

const {createProxyMiddleware} = require("http-proxy-middleware");

module.exports = function (app) {
//   app.use(
//     createProxyMiddleware("/apis", {
//       target: "https://xxx.xxx.cn",		//  Cross domain web address required 
//       changeOrigin: true,     // Cross domain 
//     })
//   )
app.use(
    createProxyMiddleware("/api", {  //    This /api, Is the identified request path splicing , Tell request , When what request , You need to cross domain here 
      target: "https://c.m.163.com/ug",
      changeOrigin: true,     // Cross domain 
    })
  )
}
 Copy code 

And then ok La ~

Cross domain requests can be made

import React from 'react'
import ReactDom from 'react-dom'
import axios from 'axios'

(async function() {
  const url = '/api/wuhan/app/data/list-total?t=' + new Date().getTime()
  const res = await axios.get(url)
  console.log(res)
}())
 Copy code 

\

The second step is to have a deep pit (React Agent exception in Proxy is not a function)

problem : Official proxy The configuration document (www.html.cn/create-reac…

as follows

const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(proxy('/api', { target: 'http://xxx.xxx.com' }));
};
 Copy code 

The startup error is as follows

proxy is not a function
error Command failed with exit code 1.
 Copy code 

Solution : Inquire about npm Of http-proxy-middleware, Find out 1.x Major changes have been made .

file (www.npmjs.com/package/htt…

Write it correctly :

const {createProxyMiddleware} = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(createProxyMiddleware('/api', { target: 'http://localhost:5000/' }));
};

//  perhaps 

const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(proxy.createProxyMiddleware('/api', { target: 'http://localhost:5000/' }));
};
 Copy code 

Slice tail : http.js To configure

import axios from 'axios'
import qs from 'qs'

axios.defaults.baseURL = 'https://c.m.163.com/ug/'
axios.defaults.withCredentials = true
axios.defaults.timeout = 100000

let http = { post: '', get: '' }

http.post = (api, data) => {
    const params = qs.stringify(data)
    return new Promise((resolve, reject) => {
        axios.post(api, params).then(r => {
            resolve(r)
        }).catch(e => {
            reject(e)
        })
    })
}

http.get = (api, data) => {
    const params = qs.stringify(data)
    return new Promise((resolve, reject) =>{
        axios.get(api, params).then(r => {
            resolve(r)
        }).catch(e => {
            reject(e)
        })
    })
}

export default http
 Copy code 

Last

official account : Xiao he grows up , Buddhist Geng Wen , They are all the pits they have stepped on or learned

Interested friends are welcome to pay attention to me , I am a : He Xiaoshi . Let's make progress together

A little busy recently , The article may have some water , If you have problems, you can pay attention to my official account. , Communicate together

The comments are written in the code , See forgiveness

copyright notice
author[He Xiaoshi],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827020643619Q.html

Random recommended