1、一個基本的代理
module.exports = { //... devServer: { proxy: { '/api': 'http://localhost:3000' } } };
/api/users
將請求代理到的請求http://localhost:3000/api/users
。
2、重寫路徑代理
如果不想/api
傳遞,需要重寫路徑:
module.exports = { //... devServer: { proxy: { '/api': { target: 'http://localhost:3000', pathRewrite: {'^/api' : ''} } } } };
/api/users
將請求代理到的請求http://localhost:3000/users
。
3、支持https
默認情況下,是不接受在HTTPS上運行且具有無效證書的后端服務器。如果需要,可以像這樣修改配置:
module.exports = { //... devServer: { proxy: { '/api': { target: 'https://other-server.example.com', secure: false } } } };
4、將請求代理到同一目標
如果要將多個特定路徑代理到同一目標,則可以使用具有context
屬性的一個或多個對象的數組:
module.exports = { //... devServer: { proxy: [{ context: ['/auth', '/api'], target: 'http://localhost:3000', }] } };
參考:https://webpack.js.org/configuration/dev-server/#devserverproxy