Vue.js API代理疑问:posts/1应配置在proxyTable还是Vue文件?
posts/1? Great question! Let me break this down clearly for you so you can get your proxy working exactly as intended.
The Short Answer
The posts/1 portion belongs in your .vue file's axios request, not in the proxyTable configuration. The proxyTable only handles matching the /api prefix and redirecting it to your target base URL—any path that comes after /api will automatically be appended to the target URL.
Step-by-Step Configuration Example
1. Set Up proxyTable (in vue.config.js for Vue CLI 3+, or config/index.js for older projects)
Here’s the correct proxy configuration to map /api requests to your target API:
module.exports = { devServer: { proxy: { '/api': { target: 'http://jsonplaceholder.typicode.com', changeOrigin: true, // Critical for avoiding CORS issues and ensuring proper host header forwarding pathRewrite: { '^/api': '' } // Removes the `/api` prefix from the request path before sending to the target } } } };
target: The base URL of your external API server.pathRewrite: This rule strips the/apiprefix from your request, so/api/posts/1becomes/posts/1when sent to the target.changeOrigin: Ensures the proxy server sends the request with the target domain’s host header, which many APIs require for validation.
2. Make the Request in Your .vue Component
In your Vue file, use axios to send a request to /api/posts/1—the proxy will handle routing it to http://jsonplaceholder.typicode.com/posts/1 automatically:
import axios from 'axios'; export default { mounted() { axios.get('/api/posts/1') .then(res => { console.log('Fetched post:', res.data); }) .catch(err => { console.error('Request failed:', err); }); } };
How It All Works Together
When your app sends a request to /api/posts/1:
- The dev server’s proxy intercepts the request because it matches the
/apipattern. - It uses
pathRewriteto remove the/apiprefix, leaving/posts/1. - It appends this remaining path to the
targetURL, creatinghttp://jsonplaceholder.typicode.com/posts/1. - The proxy forwards the request to that full URL, then sends the response back to your app as if it came from your local dev server.
Key Takeaway
Keep dynamic or endpoint-specific paths (like posts/1) in your axios requests. The proxyTable only needs to handle the base prefix-to-domain mapping. This setup lets you reuse the same proxy config for all /api-prefixed requests, no matter what specific endpoint you’re hitting.
内容的提问来源于stack exchange,提问作者ofey

