Axios Pit record + interceptor using +vue CLI Proxy cross-domain proxies

Source: Internet
Author: User
Tags blank page server port

1, small mention the Vue CLI scaffolding front end of the back-end data interface when the local agent cross-domain issues, such as my local localhost access interface http://40.00.100.100:3002/is to cross-domain, equivalent to the browser set a threshold, Will error XMLHttpRequest can not load http://40.00.100.100:3002/. Response to preflight request doesn ' t pass access control .... Why cross-domain homologous non-homologous to check it, in Webpack configuration proxytable on OK.

as follows: Config/index.js

Dev: {//proxytable Parameters Add the followingproxytable: {'/api': {target:'http://40.00.100.100:3002/',//set the interface domain name and port number you are calling don't forget to add HTTPChangeorigin:true, Pathrewrite: {'^/api':'/'//This is understood to replace the address in target with '/api ', which is replaced by API when we tune the interface in the next component, for example, I want to
Call 'http://40.00.100.100: 3002/user/add ', directly write '/api/user/add ' can, but the actual interface is not/API, so need to rewrite } } },

Try it, cross-domain success, but note that this is only the development environment (DEV) solves the cross-domain problem, the production environment in the real deployment to the server if the non-homologous or cross-domain issues, such as we deploy the server port is 3001, requires a front and back end of the tune, The first step front-end we can be divided into production production and development development two environments, respectively, in Config/dev.env.js and prod.env.js in the development/production environment, respectively, configure the requested address Api_host, In the development environment we use the proxy address API configured above, the production environment with the normal interface address, so configure

 module.exports = merge (Prodenv, {node_env:   "  "development"     ", //  development environment  Api_host: " /api/  " })   
Module.exports = {  'production',// production environment  Api_host: ' "http://40.00.100.100:3002/" ' }

Of course, both the development and production environments can request http://40.00.100.100:3002/directly. After the test is configured, the program will automatically determine whether the current development or production environment, and then automatically match the Api_host, we can use the Process.env.API_HOST in any component of the address such as

Instance.post (process.env.api_host+'user/login'this. form)

Then the second step back-end server configuration Cros cross-domain, that is, access-control-allow-origin:* allows all access to the meaning.

Comprehensive: Under the environment of development we can configure a proxy agent can cross the domain, the real production environment also need back-end coordination. A great God said: This method IE9 and the following does not work, if the need for compatibility, the best way is the backend in the server port to add an agent, the effect is similar to the development of Webpack agent.

2, Axios does not support Vue.use () way declaration use, looked at all near the same Axios document did not mention this, the recommended way

// The following declarations are used in Main.js  from ' Axios ' ; Vue.prototype. $axios=Axios; // You can do this in other Vue components. $axios call using the

3, Axios send Get/post request problem

When sending a POST request, you typically set the Content-type, the type of content to send.

Application/json refers to sending a JSON object, but stringify it in advance.

Application/xxxx-form means send? a=b&c=d format, you can use the method of QS format, QS installed after the Axios will be installed automatically, only need to import the components can be.

 const  postdata=json.stringify (this  .formcustomer);   " content-type   ' :  " application /json   " }   Const  postdata=qs.stringify (this . Formcustomer); //  filter into? &= format   " content-type   ' :  " application/ Xxxx-form   "}  

4, the use of Axios interceptor

When we visit an address page, we sometimes ask us to re-login and then visit the page, that is, the authentication is invalid, such as token is lost, or token is still local, but it is not valid, so it is not possible to determine the local token value alone can not solve the problem. At this time, the server returned a 401 error, authorization error, that is, no right to access the page. We can filter this situation before sending all requests and before the operation Server responds to the data.

//HTTP request Request interceptor with token value configured with token valueaxios.interceptors.request.use (config= {        if(token) {//determine the presence of tokens before each request is sent.
If present, unify the header of the HTTP request with token, without having to manually add each requestConfig.headers.Authorization =token; } returnconfig; }, Err= { returnPromise.reject (ERR); });//HTTP response server response blocker, here intercept 401 error, and re-jump into the page to regain tokenAxios.interceptors.response.use (Response= { returnresponse; }, Error= { if(error.response) {Switch(error.response.status) { Case 401: //write code to clear tokens hererouter.replace ({path:'Login', query: {redirect:router.currentRoute.fullPath}//jump into the current page of browsing after successful login }) } } returnpromise.reject (Error.response.data)});

5, how to place the Vue project on the server, here in Tomcat as an example:

Must be configured under the template Vue-cli Webpack/config/index.js, we can seeassetsPublicPathThis key, and this thing also appeared two times, when I first packaged, just modified the bottom of theassetsPublicPath, take it from‘/‘Changed to./, and then I executed it.npm run build, after the package is successful, you can see that there will be more folders in the project.dist, there is astaticFolders, andindex.html, and then I willdistFiles under the directory are copied to the Tomcat server, you will find a blank page, but when I put it in..\webapps\ROOTdirectory, it can be accessed. The directory structure below Tomcat is as follows. But this certainly is not, and then I began to look for answers, but also according to other people's steps to do down, later found that there are some problems, there is no way to access the main page, although it has not been successful, but I did not give up, and then a comprehensive answer to what others said, made several attempts, and finally succeeded. I changed two places, that is, the value of Assetspublicpath, I use the./, I also used the WebApps under the project name tried, but did not get the results I want, and then I changed to./

Axios Pit record + interceptor using +vue CLI Proxy cross-domain proxies

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.