简体   繁体   中英

Cannot call api route from client app loaded by distant browser

I have a server where there is an api running on port 8081 and a client Vue app running on 8082.

My client app using Axios to make queries to the api using the following code.

const api = axios.create({
  baseURL: 'http://127.0.0.1:8081/api/route',
  headers: {
    'Content-Type': 'text/plain',
  },
});

The client is served by the following express server:

const express = require("express");
const cors = require("cors");

const path = __dirname + '/dist/';

const app = express();

app.use(express.static(path));

app.use(cors());

app.get('*', function (req,res) {
  res.sendFile(path + "index.html");
});

// set port, listen for requests
const PORT = 8082;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});

If I use my app directly from the server there is no problem, the query is correctly executed.

But if I load the app from a distant browser, the client is not capable to execute the query, trying to use the 127.0.0.1 of the distant browser, not the server one.

Error case with browser

Setting Axios to use the local IP of the server make the things work but the application need to be generic and it should only use the 127.0.0.1 because the app and api will always be on the same machine.

I found the solution, to make the address generic, I need to use the global variable:

window.location.hostname

That contains the hostname of the machine that runs the Vue app server.

Now when I try to make a request from distant computer, my browser is correctly using the machine hostname, not its own localhost.

This is the new Axios configuration:

const apo = axios.create({
  baseURL: `http://${window.location.hostname}:8081/api/route`,
  headers: {
    'Content-Type': 'text/plain',
  },
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM