我正在创建一个简单的反应前端与Express后端。我可以让express将JSX数据作为JSON发送给我,这样我就可以在react中获取它并将其显示为组件吗?目前我正在发送JSON数据,并将其作为组件显示在react中,它工作得很好,如何才能将JSX数据作为JSON发送?
这是到目前为止的代码,React前端:
import React, { Component } from "react";
import "./App.css";
class App extends Component {
state = { users: [] };
componentDidMount() {
fetch("http://localhost:3001/users")
.then(res => res.json())
.then(users => this.setState({ users }))
.catch(error => { });
}
render() {
return <div className="App">
<h1>Users</h1>
{this.state.users.map(user => <div key={user.id}>
{user.username}
</div>)}
</div>;
}
}
export default App;Express后端:-
var express = require("express");
var router = express.Router();
/* GET users listing. */
router.get("/", function(req, res, next) {
// Comment out this line:
//res.send('respond with a resource');
// And insert something like this instead:
res.json([
{
id: 1,
username: "samsepi0l"
},
{
id: 2,
username: "D0loresH4ze"
}
]);
});
module.exports = router;发布于 2017-08-12 23:54:28
您的实现似乎是正确的,但请求中有一个错误。
您的React组件应该请求http://localhost:3001/,或者您应该将您的Express端点更改为router.get('/users', ...。
发布于 2017-12-30 15:51:41
当您试图从express检索数据时,您正在调用/users,但是express中没有用于接收或响应此调用的代码。您需要添加一个额外的router.get("/users", function(req, res, next) { }才能使此调用工作。我不认为有任何理由通过请求返回react来发送JSX组件(我猜您陈述数据时指的是组件)。请描述您想要解决的实际问题。
https://stackoverflow.com/questions/45635079
复制相似问题