"Proxy" in package.json must be a string solutions

Today react a learning project. I want to get data from the local server.

Direct axios.get ( 'http: // localhost: 80 / api / react / header.json'), the cross-domain error.

Online search the next, you need to configure the next proxy in package.json years. OK, great God shining share step by step configured. It has suggested:

It is understood literally. . proxy must be a string, but I configured objects.

Method 1: string configuration according to it.

use:

Note that, get in the url path method without having to write the address of a local server, which means that all requests will go here. .

I was on it. If there are errors, welcome that.

 

Method 2: http-proxy-middleware plug-ins.

$ npm install http-proxy-middleware --save
$ 或
$ yarn add http-proxy-middleware

SetupProxy.js then create a file in the src directory. It reads as follows:

const proxy = require('http-proxy-middleware');
 
module.exports = function(app) {
  app.use(proxy('/api', { target: 'http://localhost:80' }));
  // app.use(proxy('/test', { target: 'http://localhost:3000' }));
  // 省略...
};

Note that this file does not need anywhere in the introduction, restart the project (npm start) can be.

Also '/ api' encounter this mean the beginning of the path will go above the target address. It is the stitching together of feeling, such as:

Equivalent to http: // localhost: 80 / api / react / header.json.

Note that, / api stitching will go up, if your path is not the word, you can use the full configuration, as follows:

app.use(proxy('/api', { 
target: 'http://localhost:80',
changeOrigin:true,
pathRewrite: {
            "^/api": "/" // 把/api 变成空
        }
 }));

Equivalent to http: // localhost: 80 / react / header.json.

Probably run up like this.

If wrong, please point out.

 

Method 3? : The node_modules in the react-scripts to delete and re-install an older version.

如: cnpm i [email protected] --save。

This method is tried a few times, have not installed successfully, it is not clear where the problem lies. .

 

Guess you like

Origin www.cnblogs.com/caimuguodexiaohongmao/p/11247636.html