【问题标题】:Expressjs server and external api callsExpressjs 服务器和外部 api 调用
【发布时间】:2021-01-19 07:05:36
【问题描述】:

我是前端开发和快递服务器的新手。当我尝试使用 react 启动 express.js 服务器时(通过 axios 调用外部 api),express.js 似乎在外部 API 调用前面添加了“localhost:3000”,因此它们失败了。

在我的 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!');
});

这导致对 www.example.com/api/ 的 API 调用变为 http://localhost:3000/www.example.com/api/

我还尝试通过以下方式过滤req:

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

但它不会改变事情...... 谁能帮帮我这个新手?

Update1 添加调用api的代码: 这是api调用:

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

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

endpoints.GET_SOMETHING 是 api URL:www.example.com/api/getSomething

【问题讨论】:

  • 你能添加你用来调用api的代码吗?
  • 你不显示你的前端代码,但是如果你想向不同的主机或端口发出请求,而不是从加载网页的地方,那么你需要构造一个完整的 URL,例如http://myhost:4000/mypath 并在请求中使用该完整 URL。
  • html中有没有baseurl标签?如果是,则将其删除:)
  • 感谢您所有的 cmets!它确实需要一个完整的 URL,现在它可以工作了!

标签: node.js reactjs express axios


【解决方案1】:

您需要在网址中添加/

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

您的端点网址也应以https://http://// 开头

【讨论】:

  • 谢谢!它现在正在工作!这比我想象的要简单得多......正在研究使用 http-proxy-middleware 制作代理并找到您的答案,现在一切都像魅力一样工作
猜你喜欢
  • 2015-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-30
  • 1970-01-01
  • 2017-03-06
  • 2018-01-30
  • 1970-01-01
相关资源
最近更新 更多