0
votes

I'm new to frontend development and express server. When I tried to start an express.js server with react (with axios calls to external apis), it seems express.js is adding 'localhost:3000' in front of the external API calls so they fail.

In my server.js:

const path = require('path');
const express = require('express');
const app = express();
const publicPath = path.join(__dirname, '.', 'dist');
const port = process.env.PORT || 3000;
app.use(express.static(publicPath));
app.get('*', (req, res) => {
  res.sendFile(path.join(publicPath, 'index.html'));
});
app.listen(port, () => {
  console.log('Server is up!');
});

Which leads to the API call to www.example.com/api/ to become http://localhost:3000/www.example.com/api/

I also tried to filter the req by writing:

app.get('*', (req, res) => {
  if (req.url.match(/\/api\//) === null) {
    res.sendFile(path.join(publicPath, 'index.html'));
  }
});

But it does not change things... Can anyone help out this newbie that is me?

Update1 Adding the code for calling the api: This is the api call:

const getSomething = () => {
  try {
    const url = endpoints.GET_SOMETHING;

    return axios.get(url);
  } catch (err) {
    console.log(err);
  }
};

endpoints.GET_SOMETHING is the api URL: www.example.com/api/getSomething

1
Could you add the code you are using to call the api? - Anish
You don't show your front end code, but if you want to make a request to a different host or port than the web page was loaded from, then you need to construct a full URL such as http://myhost:4000/mypath and use that full URL with the request. - jfriend00
Is there in html have you a baseurl tag? If yes then remove it :) - sarkiroka
Thx for all your comments! It did need a full URL and it now works! - Solitude Ever

1 Answers

1
votes

You need to put a / in the url

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

and also your endpoint url should start with https://, http:// or //