During the development process, we sometimes call third-party interfaces to request data. At this time, we will encounter a problem: cross-domain restrictions. The explanation of the cross-domain problem will not be described in detail. If you want to know, please Baidu. Generally, the cross-domain problem console will report this error:
In many cases, the background will do a request proxy for us. When the background does not help you, you can only solve it yourself. I use webpack here in Vue-cli, then we need to do proxy settings on webpack. The specific steps are as follows:
Suppose the request address is http://baidu.com/img/upload/file.
1. Write the link address to be cross-domain proxy in the dev: { proxyTable: { }} of the config/index.js file, as shown in the following figure:
Note: '/upload' is the matching item, we write '/upload' for the matching item, then when we run npm run dev to run the local service, localhost:8080/upload/file is our proxy address.
The target parameter fills in the requested address, such as a third-party interface, such as the above http://baidu.com/img/upload/file;
The changeOrigin parameter is if the interface needs to configure this parameter across domains;
The pathRewrite parameter is the rewrite address;
There is also a parameter secure, if it is an https interface, you need to configure this parameter;
2. Configure in the config/dev.env.js file, as shown in the following figure:
3. Configure in the config/prod.env.js file, as shown in the following figure:
Note: Fill in '"//baidu.com/img/upload/"' for upload here, do not need to write 'http:', remember to add '/' at the end;
At this point, the proxy configuration of webpack has been completed, you need to restart the service, and then write the request function. I use axios with qs, so the request function is:
export const uploadFile = params => { return axios.post('/upload/file', qs.stringify(params)).then(res => res.data)};
The request functions are written differently. Here I just want to express that the first parameter url of the request function should be written '/upload/file', which is equivalent to requesting http://baidu.com/img/upload/file. So far, the cross-domain problem has been solved, and the pro test is effective.
If you need to reprint, please indicate the source:
http://www.cnblogs.com/zishang91/p/8909900.html
, so that errors can be corrected in time. If there are any mistakes, please forgive me and give pointers, thank you! ! !