Rah*_*hni 7 javascript reactjs react-dom
将我的 mern 应用程序部署到 Heroku 后,GET主页上的请求('http://localhost:8000/post/')现在返回index.html而不是json data从请求中返回。我正在获取200 status代码,但响应是html. 但是,它在本地运行良好。
除了这个请求之外,所有其他请求都在工作。每当我认为我已经修复它时,Heroku 会在同一条路线上显示 json 数据而不是 UI。我假设这些问题是相关的。
我该如何解决这个问题?谢谢!
路由/控制器 - 列出帖子
router.get('/', (list))
exports.list = (req, res) => {
const sort = { title: 1 };
Post.find()
.sort(sort)
.then((posts) => res.json(posts))
.catch((err) => res.status(400).json("Error: " + err));
};
Run Code Online (Sandbox Code Playgroud)
服务器.js
require("dotenv").config();
// import routes
...
const app = express();
// connect db - first arg is url (specified in .env)
const url = process.env.MONGODB_URI
mongoose.connect(url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false,
});
mongoose.connection
.once("open", function () {
console.log("DB Connected!");
})
.on("error", function (error) {
console.log("Error is: ", error);
});
// middlewares
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
next();
});
// middleware
...
// app.use(express.static(path.join(__dirname, './client/build')))
app.use(authRoutes);
app.use(userRoutes);
app.use('/post', postRoutes);
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
app.get("/*", function (req, res) {
res.sendFile(path.join(__dirname, "./client/build/index.html"));
});
const port = process.env.PORT || 80;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Run Code Online (Sandbox Code Playgroud)
ListPosts.js
class ListPosts extends React.Component {
state = {
title: '',
body: '',
date: '',
posts: []
}
componentDidMount = () => {
this.getPosts()
}
getPosts = () => {
axios.get(`${API}/post`)
.then((response) => {
const data = response.data
this.setState({posts: [data]})
console.log(data)
})
.catch((error) => {
console.log(error)
})
}
displayPosts = (posts) => {
if (!posts.length) return null;
posts.map((post, index) => (
<div key={index}>
...
</div>
))
}
render() {
return (
<div>
{this.displayPosts(this.state.posts)}
</div>
)
}
}
export default ListPosts
Run Code Online (Sandbox Code Playgroud)
小智 9
您的请求'http://localhost:8000/'匹配两个路由处理程序
app.get("/*", function (req, res) {
res.sendFile(path.join(__dirname, "./client/build/index.html"));
});
Run Code Online (Sandbox Code Playgroud)
router.get('/', (list))
Run Code Online (Sandbox Code Playgroud)
由于您的客户端构建路由位于列表路由上方,因此它将始终返回 index.html,因为在定义路由时,优先级在 express 中很重要。
一个好的做法和解决方案是始终通过/api在所有路由之前附加以下内容来区分您的 api 路由和静态路由
app.use('api/auth', authRoutes);
app.use('api/post', postRoutes);
app.use('api/user', userRoutes);
Run Code Online (Sandbox Code Playgroud)
小智 4
由于一些答案已经提到将 API 和客户端路由分开并找到了确切的问题,我想根据我使用express. (技巧是还添加版本控制)
app.use('/api/v1/auth', authRoutes);
app.use('/api/v1/user', userRoutes);
app.use('/api/v1/post', postRoutes);
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, "client/build")));
app.get("/*", (_, res) => {
res.sendFile(path.join(__dirname, "client/build", "index.html"));
});
}
Run Code Online (Sandbox Code Playgroud)