The react project uses proxy to solve cross-domain problems in package.json

clipboard.png

as shown in the figure, using proxy to solve cross-domain, I see many blogs say that this can solve cross-domain. What is the reason for this?
A blog said that it was written in this way, and tried to report an error saying that proxy should not be an object, but should be in string format

.
"proxy": {
    "/api": {
      "target": "http://localhost:5000",
      "pathRewrite": {
        "^/api" : ""
      },
      "changeOrigin": true
    }
  }
  

react version is 16.5.2, and the backend interface uses node+mongodb, at port 5000
hoping for the help of bosses

Nov.25,2021

use a custom agent

the first step is to install http-proxy-middleware

 

Thank you for the invitation.

there is no problem with your configuration. You need to see where you send the request. You just need to change it to a relative path

.

for example, if you have a fetch (http://localhost:5000/api/userdata/) interface), you can't write it like this, otherwise you will cross-domain (because your page is port 3000 and your request is port 5000)

= >

you need to change it to fetch ('/ api/userdata/')

he will forward to the address

in proxy .

that is, the real request is http://localhost:5000/api/userdata/, and there will be no cross-domain problems

because from the browser's point of view, you just sent fetch ('http://localhost:3000/api/userdata/'), no cross-domain problems

).
Menu