React & Express server not getting api requests in production /build

∥☆過路亽.° 提交于 2020-04-17 22:50:21

问题


I have a React app running successfully locally and all api requests are successfully running from a separate server. When I run a build, the path to the api server is lost and no data is loaded. Below are a few screenshots...

Loading data successfully from api.

Pointing IIS to react /build folder using localhost:80. No data loading.

Here is an example of an api call in my node/express server/index.js file

app.get('/api/company', (req, res) => {
api_helper.GET('https://****/api/company')
    .then(response => {
        res.json(response)
    })
    .catch(error => {
        res.send(error)
    })

})

My package.json file has the url of the express proxy (running in the background).

"proxy": "http://localhost:5000/",

My question is, why isnt the api loading in production /build? I just get this...

Request URL: http://localhost/api/site Request Method: GET Status Code: 404 Not Found Remote Address: [::1]:80 Referrer Policy: no-referrer-when-downgrade

but when just running locally (npm start) I get this and data loads from api.

Request URL: http://localhost:3000/api/site Request Method: GET Status Code: 304 Not Modified Remote Address: 127.0.0.1:3000 Referrer Policy: no-referrer-when-downgrade

Any help appreciated, driving me mad! Thanks.


回答1:


For anyone else struggling with this, I figured it out..

I had to add this to my express server.js file in the root folder of my project.

    app.use(express.static(path.join(__dirname, 'build')));

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname, 'build', 'index.html'));
  });

I then pointed to the address where express is running, in my case http://localhost:5000

This worked.

I also then set up a rewrite rule in IIS to point localhost and our domain name to localhost:5000

All working now, hope it helps someone else.




回答2:


Thanks for your info. I am quite new to ReactJS and I also encountered similar problems when I created my production build. Actually I had added similar things like

app.use(express.static(<build_folder_dir>));

in my Express Server before then I came to search and see your post. Anyway, I did not add something like the second line of your code and my API calls are written in router created in a separate js file.

app.use('/api/some_path', <imported_router>);

In the exported router object, codes are written like this:

router.get('/some_sub-path')

To make API calls, I used axios in my react app

axios.get(
      "/api/some_path"+"/sub-path?param_1="+<param_value>,
      {
        headers:{
          "Content-Type":"application/json",
          <some headers>
        }
      }
).then((res)=>{<Some codes using the res.data.<any param in body>>})

Finally,I added these lines in the server.js

app.get('/*', function(req, res) {
    res.sendFile(path.join(__dirname, <path of the index.html in the build dir>), function(err) {
            if (err) {
              res.status(500).send(err)
            }
          })

  })

Yet, I made a stupid mistake that my app crashed because the app.get overwrite the settings in router. Just a reminder, if you enable any API calls in GET method, use regex to exclude the pattern for making API calls.




回答3:


After much testing I discovered, you must put the routes before

Wrong Example:

app.use(express.static(path.join(__dirname, 'build')));

app.get('/', function (req, res) {
    res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

app.use('/', routes);

Right Example:

app.use('/api', routes);

app.use(express.static(path.join(__dirname, 'build')));

app.get('*', function (req, res) {
    res.sendFile(path.join(__dirname, 'build', 'index.html'));
});


来源:https://stackoverflow.com/questions/57907473/react-express-server-not-getting-api-requests-in-production-build

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