GET请求返回index.html doc而不是json数据 [英] GET request returns index.html doc instead of json data
问题描述
将我的Mern应用程序部署到Heroku之后,主页('http://localhost:8000/post/')
上的 GET
请求现在返回<来自请求的code> index.html 而不是 json数据
.我正在获取 200状态
代码,但响应为 html
.但是,它可以在本地正常工作.
除此请求外,所有其他请求都可以正常工作.每当我认为已修复它时,Heroku都会在同一条路径上显示json数据而不是UI.我假设这些问题是相关的.
After deploying my mern app to Heroku, the GET
request on the home page ('http://localhost:8000/post/')
is now returning index.html
instead of json data
from the request. I'm getting 200 status
code but the response is html
. However, it works fine locally.
All the other requests are working except this one.
Whenever I think I've fixed it, Heroku displays the json data instead of the UI on this same route. I'm assuming that these issues are related.
我该如何解决?谢谢!
路线/控制器-列出帖子
route/controller - list posts
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));
};
server.js
server.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}`);
});
ListPosts.js
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
推荐答案
正如已经提到的一些答案将您的API和客户端路由分开,并找到了确切的问题,我只想根据我的建议添加一些建议使用 express
服务您的React应用的经验.(技巧还包括添加版本控制)
As some of the answers already mentioned seperating your API and client routes and found the exact issue, I would like to just add a little bit of recommendations based on my experience with serving your react app using express
. (Trick is to also add versioning)
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"));
});
}
这篇关于GET请求返回index.html doc而不是json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!