node和reactjs axios服务器请求返回index.html文件而不是json

时间:2017-12-04 16:09:27

标签: node.js reactjs api express axios

我已经设置了我的项目,反应前端是由webpack编译的,服务器是在节点和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 route / 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 url,因此被重定向到只是服务index.html文件。

任何帮助?

干杯

2 个答案:

答案 0 :(得分:0)

也许这是违法行:

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'));
});

答案 1 :(得分:0)

根据webpack docs,您可以按如下方式指定代理设置

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

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

此外,值得注意的是,他们建议您通过path.join(__dirname, "dist")使用绝对路径进行contentBase设置。