前言
本節(jié)我們將通過redux中間件,用ajax方法對服務器取得數(shù)據(jù),用到的包:
- superagent:封裝了ajax方法
- http-proxy:解決跨域ajax問題
配置
helpers/ApiClient.js
對superagent進行重新封裝,以適應我們應用需要,這里就不貼代碼了。
redux/middleware/clientMiddleware.js promise
中間件,用于獲取服務器數(shù)據(jù)。
redux/modules/info.js inforBar
的reducer
文件,主要是action,types
components/InfoBar/InfoBar.js, container/App/App.js有部分修改,這里就不做說明了。
注意:添加新的組件和中間件,要將他們添加到redux/create,redux/modules/reducers.js
中
最后在package.json,中添加命令,同時啟動APP 與 API SERVER
"dev": "concurrently --kill-others \"npm run start-dev\" \"npm run start-api\""
好了完成以上工作后,啟動命令npm run dev
,然后訪問http://localhost:3000
,我們的infobar
出現(xiàn)在我們頁面的底部。點擊后發(fā)現(xiàn)并沒有出現(xiàn)我們想要的服務器數(shù)據(jù),打開chrome的調(diào)試工具發(fā)現(xiàn),是不允許我們訪問3030,出現(xiàn)跨域的問題,這里我們用代理服務來解決
代理服務
修改src/server.js
添加如下代碼
...
import httpProxy from 'http-proxy'
const targetUrl = 'http://' + appConfig.apiHost + ":" + appConfig.apiPort;
const proxy = httpProxy.createProxyServer({
target:targetUrl
})
...
app.use(express.static(path.join(__dirname,'../public')))
//代理服務器
app.use('/api',(req, res) =>{
proxy.web(req, res, {target: targetUrl})
})
proxy.on('error', (error, req, res) => {
let json;
if (error.code !== 'ECONNRESET') {
console.error('proxy error', error);
}
if (!res.headersSent) {
res.writeHead(500, {'content-type': 'application/json'});
}
json = {error: 'proxy_error', reason: error.message};
res.end(JSON.stringify(json));
});
...
注意:添加api代理服務器后,要把將action中的promise,指向代理服務器,然后再次運行,訪問出現(xiàn)服務器時間。
Next
服務器數(shù)據(jù)異步取得