簡體   English   中英

節點和reactjs axios服務器請求返回index.html文件而不是json

[英]node and reactjs axios server request returning index.html file instead of json

我已經用webpack編譯了一個React前端和在node和express上運行的服務器來設置我的項目。

當我部署到生產環境時,我對服務器的請求正在返回“ dist”文件夾中的index.html文件,而不是包含數據的json。

我的webpack編譯輸出位於./dist位置。

這是我的server.js文件的路由部分:

if (process.env.NODE_ENV === 'production') {
  app.use(express.static('dist'));
  const path = require('path');
  app.get('/', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
  });
}
// Use our router configuration when we call /
app.use('/', router);

這是我的webpack配置文件的一部分:

var HtmlWebpackPlugin = require('html-webpack-plugin');
var HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
  template: __dirname + '/client/index.html',
  filename: 'index.html',
  inject: 'body'
});

module.exports = {
  entry: [
    './client/index.js'
  ],
  output: {
    path: __dirname + '/dist',
    filename: 'index_bundle.js'
  },
  devServer: {
    inline: true,
    contentBase: './dist',
    port: 8080,
    proxy: { '/api/**': { target: 'http://localhost:3000', secure: false } }
  },
  module: {
    loaders: [
      {test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: {presets: ['es2015','react'], plugins: ['transform-es2015-destructuring', 'transform-object-rest-spread']}},
        {test: /\.jpe?g$|\.gif$|\.svg$|\.png$/i, loader: 'file-loader?name=/images/[name].[ext]'},
        {test: /\.css$/, loaders: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader','resolve-url-loader']},
        {test: /\.scss$/, loaders: ['style-loader', 'css-loader','postcss-loader', 'sass-loader','resolve-url-loader']}
        ]
  },
  plugins: [HTMLWebpackPluginConfig]
};

我的請求如下(api路由/ api / chefs返回帶有用戶配置文件的json(已在開發中測試):

export function listChefs() {
  return function (dispatch) {
    axios.get('/api/chefs')
      .then((response) => {
        dispatch({
          type: LIST_CHEFS,
          payload: response.data
        });
      })
      .catch((err) => {
        errorHandler(dispatch, 'There was a problem. Please refresh and try again.');
      });
  };
}

看來我使用axios從客戶端發出的調用實際上正在擊中無法識別的api網址,因此被重定向到僅服務器index.html文件。

有什么幫助嗎?

干杯

也許這是違規行:

app.get('/*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
});

因為這會捕獲您的所有請求。 如果將/*更改為/是否可以解決該問題?

我認為請求無法發送到您的路由器,因為/*捕獲了所有請求並返回了index.html頁面。

嘗試:

app.get('/', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'dist', 'index.html'));
});

根據webpack文檔 ,您可以指定代理設置,如下所示

proxy: {
  "/api": {
    target: "https://other-server.example.com",
    secure: false
  }
}

注意“ / api”而不是“ / api / **”。

此外,可能值得注意的是,他們建議通過path.join(__dirname, "dist")為contentBase設置使用絕對路徑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM