Detailed description of the Cross-origin problem solution in the vue-cli development environment, vue-cli
Problems that must be encountered during frontend and backend separation development-Cross-origin. When using vue for development, we started to solve cross-domain problems. CORS (Cross-origin resource sharing) is used ). Add Access-Control-Allow-Origin in the Response Header in the background. In this way, you can call the background interface across domains.
A few days ago, I accidentally saw a proxyTable attribute in the index. js file of config. The configuration can solve the cross-origin Problem of the development environment.
API proxy during development
When you integrate this template with an existing backend, you usually need to access the backend API when using the dev server. To achieve this, we can run the dev server and the API backend in parallel (or remotely), and let the dev server proxy all API requests to the actual backend.
To configure proxy rules, edit dev. proxyTable option config/index. js. The dev server is using http Proxy Middleware for proxy, so you should refer to its documentation for detailed usage. However, this is a simple example:
// Config/index. jsmodule. exports = {//... dev: {proxyTable: {// proxy all requests starting with/api to jsonplaceholder '/api': {target: 'http: // jsonplaceholder.typicode.com ', changeOrigin: true, pathRewrite: {// The rewrite is required. If processing is performed on the server side, do not use this section '^/api ':''}}}}}
In the preceding example, the proxy request/api/posts/1 is sent to http://jsonplaceholder.typicode.com/posts/1.
If
pathRewrite: { ‘^/api': ‘api' },
Send the proxy request/api/posts/1 to http://jsonplaceholder.typicode.com/api/posts/1.
URL matching
In addition to static URLs, you can also use the glob mode to match URLs, such as/api /**. For more information, see context matching. In addition, you can provide an option that filters can be user-defined functions to determine whether a request should be proxied:
proxyTable: { '*': { target: 'http://jsonplaceholder.typicode.com', filter: function (pathname, req) { return pathname.match('^/api') && req.method === 'GET' } }}
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.