[英]Not receiving the data from Node JS and use it in React JS
我试图弄清楚如何连接 NodeJS 并将一些数据发送到 React JS 以供使用。 当我访问后端时正在发送信息,但 React JS 收到一个空对象 {}。 我不确定我做错了什么。 问题可能与CORS有关吗? 还是我必须使用 JSON.parse(r)? 没有把握。
索引.js
const a = "sup"
app.get("/", (req,res)=>{
console.log("someone is here")
res.status(200).json({
data:a
})
})
app.listen(3000, ()=>{
console.log("Server is running")
})
主页.jsx
class Homepage extends Component {
state = {
authenticated: false,
data:""
};
async componentDidMount(){
const url = "http://localhost:3000"
const r = await fetch(url, {
mode: "no-cors",
method: "GET",
headers:
{"Access-Control-Allow-Origin": "*"}
})
const data = await JSON.stringify(r)
console.log(data)
}
render() {
return ( <h1>{this.state.data}</h1> );
}
}
UDPATE:
我有一个端口问题使用问题和 componentDidMount() 的错误使用。 我设法按照用户的建议改进了代码。 NodeJS 和 ReactJS 指向端口 3000。我重新分配了端口 (NodeJS:3000, ReactJS:4000)。 ReactJS 现在正在对“ http://localhost:3000 ”进行 fetch 调用。 但是,我现在收到 2 个错误:
1) Failed to load resource: net::ERR_EMPTY_RESPONSE
2) Uncaught (in promise) TypeError: Failed to fetch
索引.js
const express = require("express")
const app = express()
const cors = require("cors")
const a = "sup"
app.use(cors({
origin:"http://localhost:4000",
methods:"GET,HEAD,PUT,PATCH,POST,DELETE",
credentials:true
}))
app.use((req,res,next)=>{
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization")
})
app.get("/", (req,res)=>{
console.log("someone is here")
res.status(200).json({
data:a
})
})
app.listen(3000, ()=>{
console.log("Server is running")
})
主页.jsx
import React, { Component } from 'react';
class Homepage extends Component {
state = {
data:[]
};
componentDidMount(){
const url = "http://localhost:3000"
fetch(url)
.then(r=>r.json())
.then(data=>this.setState({data}))
}
render() {
return ( <h1>{this.state.data ? this.state.data : "loading"}</h1> );
}
}
export default Homepage;
确保您已安装 express 并初始化为 const 应用程序。 然后:
在后端:
const data = "Sup" app.use( "/", (req, res)=>{ res.status(200).send(data); } );
在前端 - 内部 componentDidMount:
const url="http://localhost:3000" axios.get(url).then(response => response.data) .then((data) => { this.setState({ data: data }) console.log(this.state.users) })
class Homepage extends Component {
constructor(props){
super(props);
this.state = {
authenticated: false,
data: ""
};
}
componentDidMount() {
const url = "http://localhost:3000"
fetch(url)
.then(response => response.json())
.then(data => this.setState({
data: data
}));
}
render() {
return ( < h1 > {
this.state.data ? this.state.data : 'loading';
} < /h1> );
}
}
请更新您的类组件。 componentDidMount() 中的提取不符合预期。 您不需要在 fetch 中使用 await,因为这个异步操作一旦完成,状态就会更新,并且 react 会呈现更新。 请注意您通过 API 发送的响应并相应地设置状态。 在这里,我已经根据您在问题中提供的 api 示例设置了数据。 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.