我在運行我的前端反應代碼時嘗試運行我的API時遇到了問題。我使用webpack和webpack開發服務器,但問題似乎是他們運行自己的服務器,而我的apis由另一臺運行。我想我可以讓我的應用程序完全運行在我的快速後端,但無法以某種方式使用webpack dev服務器來運行這兩個應用程序。我的後端快遞節點看起來像這樣使用與Webpack綁定的React測試API
const express = require('express');
const bodyparser = require('body-parser');
const app = express();
require('./api/findMedia.js')(app)
var PORT = process.env.PORT || 8080;
const server = app.listen(PORT,() => {
console.log('server is working : ')
})
我的webpack配置看起來像這樣。您可以忽略我的代理密鑰。我正在測試webpack dev服務器以同時運行我的express服務器。
var webpack = require("webpack");
var path = require('path');
module.exports = {
entry: {
app: "./src/app.js"
},
output: {
filename: "build/bundle.js",
sourceMapFilename: "build/bundle.map"
},
devtool: '#source-map',
devServer : {
historyApiFallback : true,
hot : true,
inline: true,
host: 'localhost',
port: 3000,
stats: 'errors-only',
proxy : {
'/api': {
host: 'localhost',
protocol: 'http',
port: 8080
}
}
},
plugins : [new webpack.HotModuleReplacementPlugin({multiStep: true})],
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015']
}
},
{
test: /\.css$/,
loader: 'style!css'
}
]
}
}
,最後我把它與使用Axios公司一個簡單的POST請求的前端和我componentdidmount內
componentDidMount(){
axios({
method: 'post',
url: '/find/media'
}).then((response)=>{
console.log('post request to mongo data from front end a success: ' + response)
console.log(response.data.findArticles)
}).catch((error)=>{
console.log('error'+error)
})
}
哇,謝謝!我有個問題。當你編寫'proxy:{/'api':'http:// localhost:8080' }'你是否想用這個代替我當前的代理?那麼另一個'proxy:'/ api':{target:'http:// localhost:8080', rewritePath:{'^/api':''} } }'你寫了什麼?我嘗試更換第二個代理,並將我的前端axios調用更改爲api/find/media,在運行devServer後,我在前端獲得了504。 –
第一個代理是如果您的快速路由器正在尋找以/ api開頭的路由 - dev服務器會將整個路徑發送到您的代理(express)。 第二個代理是如果你想重寫所有以/ api開頭的調用 - 從頭開始刪除/ api。因此,如果您請求/ api/find/media,它會將其重寫爲/ find/media。 對於axios調用,你是用/開頭的嗎?/api/find/media或只是api/find/media? rewritePath是一個正則表達式字符串,在通話開始時專門針對/ api。明確表達您的要求嗎? – callmeroot