【发布时间】:2018-05-14 12:52:50
【问题描述】:
我已在我的 react 应用程序中将代理添加到 package.json,代理服务器已启动并在端口 3001 上运行 - 我可以使用浏览器访问它。
我尝试过同时使用 axios 和 fetch,这似乎并不重要。如果您想查看,这里是link to the repo。
否则,这是我的 react 应用程序中的 package.json:
{
"name": "client",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:3001/",
"dependencies": {
"axios": "^0.17.1",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-scripts": "1.0.14"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
我的超级简单服务器...
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
const PORT = process.env.PORT || 3001;
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("client/build"));
app.get("/data", function(req, res){
res.send({someData: 1234});
});
app.listen(PORT, function() {
console.log("???? ==> API Server now listening on PORT ${PORT}!");
});
在我的 App.js 中,我尝试在 componentDidMount 函数中调用 API。
componentDidMount(){
fetch("/data").then((data) => console.log(data));
axios.get('/data').then(data => console.log(data));
}
这两个 API 调用都返回 404,并且 url 为 http://localhost:3000/data
有什么想法吗?
【问题讨论】: