Detailed description of how Vuejs2.0 uses proxyTable to implement cross-origin requests, vuejs2.0proxytable
Preface:
When a local project requests a remote server interface, it will inevitably encounter cross-domain problems, even if Access-Control-Allow-Origin: * is set :*, it is also a headache when you need to locally store cookies to log on. Here I will introduce a solution to configuring proxy in vue-cli.
In ~ The/config/dev-server.js uses a very powerful http-proxy-middleware package. For more advanced usage, see its documentation.
Usage:
For example, the remote server we want to request is http: // 192.168.400: 3000.
proxyTable: { '/api/': { target: 'http://192.168.400:3000', changeOrigin:true, //set the option changeOrigin to true for name-based virtual hosted sites pathRewrite: { '^/api': '/api' } }, },
- Enable proxy by setting changeOrigin: true
- PathRewrite indicates the rewrite path.
Example:
For example, the interface to be requested is http: // 192.168.400: 3000/api/main/getUserInfo. action.
this.$http.post('/api/main/getUserInfo.action') .then(res=>{ console.log(res) })
Follow-up:
In actual work, we also need to do something else, such as configuring baseUrl in axios:
/*** Created by Administrator on April /4/11. */import axios from 'axios '; // Add the response interceptor axios. interceptors. request. use (function (config) {// configure return config;}, function (error) {return Promise. reject (error) ;}); axios. interceptors. response. use (function (response) {// configure return response;}, function (error) {return Promise. reject (error) ;}); var http = axios. create ({timeout: 8000,/* set the request timeout time */baseURL: 'http: // 192.168.400: 3000 ',}); // Alter defaults after instance has been createdhttp. defaults. headers. common ['authorization'] = ''; export default http;/** export http, reference import http from 'in mainjs '. /config/axiosConfig '; Vue. prototype. $ http = http ;**/
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.