How to solve the cross-domain problem between the local front-end service and the third-party interface?

problem description

my brother often encounters a problem: the local npm run dev runs a front-end project, and the call to the third-party API is restricted by the same origin policy. Get requests can be solved by jsonp (generally supported by the APIs encountered at present), but the post interface does not work, and only the online environment is normal. How to implement local debugging?


there are many

solutions.
  1. if the back-end code can be changed, add the response header directly and solve the problem through cors
  2. build a service with node and do a job of forwarding http requests
  3. nginx Agent
  4. understand the functions of webpack-dev-server 's proxy to help you act as an agent in the development environment

    recommend the fourth solution

Link description

module.exports = {
  //...
  devServer: {
    proxy: {
      '/api': 'http://localhost:3000'
    }
  }
};

Cross-domain common solution:

  • jsonp (disadvantages only support get)
  • cors (cross-domain resource sharing mode requires back-end cooperation)
  • proxy (not dependent on backend)

if you are just debugging the development environment, use webpack to provide devServer to configure the agent. For more information, click here

Menu