http-proxy-middleware手動配置代理解決跨域問題

基於官方腳手架搭建react單頁應用程序

快速開始:

npx creat-react-app myApp
cd myApp
npm start

打開http://localhost:3000/ 查看你的應用
此時我們就可以在本地開始開發自己的項目了

問題來了:本地開發時如何解決前後端跨域問題??

問題描述:本地開發項目時,調用後端接口遇到跨域問題:
例如本地http://localhost:3000
而後端接口地址爲:http://dev-insurance.com/dw-insurance-api
此時需要解決跨域問題才能正常調用後端接口拿到數據,並展示在頁面上。

解決:
手動配置代理

注意:此功能適用於 [email protected] 及更高版本。

  1. 使用npm或者yarn 安裝http-http-proxy-middleware
$ npm install http-proxy-middleware --save
$ # 或
$ yarn add http-proxy-middleware
  1. 創建src/setupProxy.js,並將以下內容放入該文件中
const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  // ...
};

你現在可以根據需要註冊代理!以下是使用上述 http-proxy-middleware 的示例:

//注意: 你無需在任何位置導入此文件。 它在啓動開發服務器時會自動註冊。
const proxy = require('http-proxy-middleware');

module.exports = function(app) {
    app.use(
        '/api',//表示請求的接口以/api/開頭
        //例如請求後端接口http://dev-insurance.com/dw-insurance-api/api/login
        //fetch('/api/login').then()
        createProxyMiddleware({
            target: 'http://dev-insurance.com/dw-insurance-api', // 目標服務器 host
            changeOrigin: true, // 默認false,是否需要改變原始主機頭爲目標URL
            // ws: true,                         // 是否代理websockets
            // pathRewrite: {
            //     '^/api/old-path' : '/api/new-path',     // 重寫請求,比如我們源訪問的是api/old-path,那麼請求會被解析爲/api/new-path
            //     '^/api/remove/path' : '/path'           // 同上
            // },
            // router: {
            //     // 如果請求主機 == 'dev.localhost:3000',
            //     // 重寫目標服務器 'http://www.example.org' 爲 'http://localhost:8000'
            //     'dev.localhost:3000' : 'http://localhost:8000'
            // }
        })
    )
}

注意: 你無需在任何位置導入此文件。 它在啓動開發服務器時會自動註冊。

  1. 重新npm start即可
  2. 舉例應用:fetch 請求訪問後端http://dev-insurance.com/dw-insurance-api/api/login 登錄接口
handleClickbtn(){
	fetch('/api/login', {
		  method: 'POST', // or 'PUT'
		  body: JSON.stringify(data), // data can be `string` or {object}!
		  headers: new Headers({
		    'Content-Type': 'application/json'
		  })
	}).then(res => res.json())
	.catch(error => console.error('Error:', error))
	.then(response => console.log('Success:', response));
}
<button onClick={this.handleClickbtn.bind(this)}>登錄</button>

參考:
https://www.html.cn/create-react-app/docs/proxying-api-requests-in-development/

https://segmentfault.com/a/1190000016199721

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章