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

假如想象 提交于 2020-08-22 07:09:07

问题


I have setup my project with a react frontend being compiled by webpack and the server running on node and express.

When I deploy to production my requests to the server are returning the index.html file in the 'dist' folder rather than the json with the data.

My webpack compiled output is at the location ./dist.

Here is the routing part of my server.js file:

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

Here is part of my webpack config file:

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]
};

My request is as follows (the api route /api/chefs returns a json with user profiles (tested in development):

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

It seems as though the call that I am making from my client using axios is actually hitting the api url that isn't being recognised and therefore is being redirected to simply server the index.html file.

Any help?

Cheers


回答1:


perhaps this is the offending line:

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

becuase this catches all your requests. If you change /* to / does that fix it?

I think the request can't make it to your router because /* catches all requests and returns the index.html page.

try:

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



回答2:


According to the webpack docs, you can specify the proxy setting as follows

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

Notice the "/api" rather than "/api/**".

Also, it may be worth noting that they recommend using absolute paths via path.join(__dirname, "dist") for the contentBase setting.



来源:https://stackoverflow.com/questions/47637435/node-and-reactjs-axios-server-request-returning-index-html-file-instead-of-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!