SoFunction
Updated on 2025-04-05

vue set proxyTable parameters for proxy cross-domain

What is a proxy cross-domain

There is a homologous policy between browsers. For security reasons, data is not allowed between different domains, except for a few special examples

Tags such as <img>, <script>, <audio> can be cross-domain, but they are usually in the form of get. If you use js axios to obtain remotely, it will trigger the same-origin policy, unless your server code sets the header to allow you to access, which is obviously unreasonable! . Isn't it popular to separate the front-end and back-end now? The back-end code has been eliminated and only the front-end is left. How should I get the two-dimensional code in the front-end? I feel that it is so troublesome and difficult to use cross-domain. It may not be possible. At this time, you can use the proxy to cross-domain.

Proxy cross-domain principle

The so-called proxy is to replace the front-end but use the back-end to issue http requests. Just like in the scaffolding of vue, if you want to run the project, you need to enter npm run dev or npm run start. This command actually opens the node server it has configured. The proxy of vue scaffolding uses node to replace the front-end to initiate http requests. Since it is not a request initiated by the browser, isn't that easy?

How to proxy cross-domain vue scaffolding, find the file in the config folder, there is a dev in the file, find proxyTable{} in it, and modify it

proxyTable: {
   '/api': {
    target: '/',//The domain you want to cross    changeOrigin: true,
    pathRewrite: {
     '^/api': '/api',
    },
    headers:{
     // Here you can stack headers for setting    }
   },
  },

where target is the address you want to cross domain, /api is the next level path under the domain you cross. Like above, it is to obtain it./apiUnder something, then we introduce ajax package axios and do ajax

import axios from 'axios'
('/getMessage').then(()=>{})

After the above code is executed, it will automatically help you get it across domains./api/getMessageData of

Summarize

The above is what the editor introduced to you. Setting proxyTable parameters for proxying across domains is hoped to be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!