How to solve the cross-domain problem as a front end?

Have you finished a small function and written everything correctly? When checking the results of axios, you found that the console became popular, and found that the network tab should request a cross-origin problem? Yes, then It is a cross-domain problem, which stems from the same-origin policy of the browser. When you send ajax, the url and the request address are caused by different sources (protocol, domain name, port). At this time, you can communicate with your back-end classmates friendly .

1. If you win, then the backend solves the problem on the server side, you don't have to do anything.

2. If you are not as strong as him, , , then you can write the configuration yourself, who makes the front end the hardest. 

① Use JSONP to send requests

② Add permission to cross-domain in the request header 

        res.setHeader("Access-Control-Allow-Origin", "*");

③If you use vue-cli, then congratulations, a proxy server davServer that comes with vue cli

        In vue.config.js, module exports = { davServer:{ proxy:{ xxx } } }

All you have to do is to add an attribute in xxx: For example, if you encounter a cross-domain problem interface, they all have the prefix /api, then you can do this:

devServer: {
    // 配置代理
    proxy: {
      '/api': {
        target: '跨域接口基地址'
      }
    }
  },

Another important step is to delete the base address in your request module and make sure your target is the prefix of your interface server, otherwise it will be repeated

The meaning here is that when the request path contains /api, it will be forwarded by davServer to the target server with its own path

Then restart the project and open it to see if the data has been obtained normally.

Guess you like

Origin blog.csdn.net/qq_59650449/article/details/128413077