我正在嘗試使用 Node.js 作為后端并在前端使用 React 進行簡單的 API 呼叫。我的 Node.js 檔案沒有以 JSON 格式回傳資料,我不知道為什么。我在兩件事上需要幫助:
- 為什么我的服務器沒有以 JSON 格式回傳資料?
- 如果它開始回傳上述 JSON,我的 API 呼叫是否可以正常作業?
錯誤資訊:
react-dom.development.js:14757 未捕獲的錯誤:物件作為 React 子項無效(找到:[object Promise])。如果您打算渲染一組子項,請改用陣列。在 throwOnInvalidObjectType (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);
前端代碼(反應):
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()})
uj5u.com熱心網友回復:
Content-Type應該application/json在服務器代碼中。
更改onClick="{fetcher()}"為onClick="{fetcher}",因為您希望僅在單擊按鈕時呼叫它,而不是在渲染時立即呼叫。我還建議將函式移到您的上方return,以便更好地組織您的代碼。如上所述Senthil,您可能還需要在 API 呼叫中使用http而不是https。
uj5u.com熱心網友回復:
使用 http 呼叫本地服務 http://localhost:8000/ 。測驗服務器端,即 postman 或 curl 請求中的節點服務呼叫。前任。curl -I http://localhost:8000/ 在與 React 集成之前。
您的節點腳本有一些錯誤。res.json 在 express 節點模塊中可用,但在 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"}]%
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/480889.html
標籤:javascript 节点.js 反应 json
上一篇:如何顯示影像而不是空陣列
