【发布时间】: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