我正在尝试使用Node.js作为后端和React在前端进行简单的API调用。我的Node.js文件没有以JSON返回数据,我不知道为什么。我有两件事需要帮助:
- 为什么我的服务器不返回JSON数据?
- 如果它开始返回上面的JSON是我的API调用好工作吗?
错误味精:
React -dom.development.js:14757未捕获错误:对象作为React子对象是无效的(found: [object Promise])。如果您打算呈现子集合,请使用数组代替。(react-dom.development.js:14757:1)后端代码:
const http = require("http");
let user={"name":"Leo"};
var server = http.createServer(function(req ,res){
res.writeHead(200, {'Content-Type': JSON});
res.json([{
number: 1,
name: 'CR7',
gender: 'male'
},
{
number: 2,
name: 'LEO',
gender: 'male'
}
]);
res.end(" done");
});
server.listen(8000);
前端代码(React):
import "./index.css";
function App() {
return (
<div className="App">
<header className="App-header">
<form>
<div>
<div className="form-group">
<label htmlFor="exampleInputEmail1">Email address</label>
<input type="email" className="form-control" />
<small className="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div className="form-group">
<label>Password</label>
<input type="password" className="form-control"/>
</div>
<div className="form-group form-check">
<input type="checkbox" className="form-check-input" />
<label className="form-check-label" >Check me out</label>
</div>
<button type="submit" onClick="{fetcher()}" className="btn btn-primary">Submit</button>
</div>
</form>
{//using state
}
function fetcher(){
fetch("https://localhost:8000/user.name",{
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then((data)=>{return data.json()})
Content-Type
在服务器代码中应该是application/json
将onClick="{fetcher()}"
更改为onClick="{fetcher}"
,因为您希望它仅在单击按钮时被调用,而不是立即渲染。我还建议将该函数移到return
之上,以便更好地组织代码。正如上面提到的Senthil
,您可能还需要在API调用中使用http
而不是https
。
使用http调用本地服务http://localhost:8000/。测试服务器端,即邮差或curl请求中的节点服务调用。例如:curl -I http://localhost:8000/在与React集成之前。
您的节点脚本有一些错误。Res.json在express node模块中可用,在HTTP模块中不可用。
查看更新后的代码和示例输出
const http = require("http");
let user={"name":"Leo"};
var server = http.createServer(function(req ,res){
res.writeHead(200, {'Content-Type': JSON});
//res.json();
res.end(JSON.stringify([{
number: 1,
name: 'CR7',
gender: 'male'
},
{
number: 2,
name: 'LEO',
gender: 'male'
}
]));
});
server.listen(8000)
示例输出:
curl http://localhost:8000/
[{"number":1,"name":"CR7","gender":"male"},{"number":2,"name":"LEO","gender":"male"}]%