[英]Sending data to and getting data from node.js?
在我的 React 代碼中,我發送了一個 'post' 和 'get' 請求。 我認為我的問題出在我的服務器端代碼中。
一般的
const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());
const posts = [
{
"postId": 1,
"id": 1,
"title": "To be or not to be",
"body": "Yes, that is the question"
},
{
"postId": 1,
"id": 2,
"title": "So What?",
"body": "What do you want"
}
];
注意:上下文,上面的代碼在問題代碼之前
已解決 1) 發布
用戶單擊“提交”一個發布請求將數據發送到服務器
問題:
1) 'req.body' 為空
fetch("http://localhost:3001/create", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(post)
})
.then(res => this.props.history.push('/posts'))
.catch(err => this.setState({error: true}))
this.setState({
title: "",
body: ""
})
app.post('/create', (req, res, next)=>{
// Request body is empty, why?
console.log(req.body);
})
解決方案:
POST 請求以 JSON 格式發送數據,因為JSON.stringify(post)
,我們需要解析這個 JSON 數據以便我們可以使用app.use(bodyParser.json());
, 我們終於得到它了。 解決了
已解決 2) 獲取
在第一個獲取請求中,我將 object 的“id”作為 URL 參數發送,並嘗試從服務器接收相應的 object,req 已正確發送。
問題:在“findPostById”function 中收到以下錯誤:
TypeError:無法讀取未定義的屬性 id
fetch(`http://localhost:3001/posts/${this.props.match.params.id}`)
.then(res=>res.json())
.then(data=>this.setState({loadedPost: data}))
.catch(err=>console.log(err))
app.get('/posts/:id', (req, res, next)=>{
// Correct, receive id
let id = req.params.id;
findPostById(id, (post, err)=>{
if(err){
console.log(err);
}
else{
res.send(post)
}
})
})
let findPostById = (id, cb)=>{
console.log(id, 'Correctly receive the id');
let post = posts.find((post)=>{
return post.id === id;
})
// Receive: 'TypeError: Cannot read property id of undefined'
console.log(post.id);
if(post){
cb(post, null);
}
else{
cb(null, new Error('Could not find post', id));
}
}
解決方案:
post.id
是“數字”類型,id 是“字符串”類型,返回post.id === id;
由於嚴格相等而導致 false 。 因此,我們將 id 轉換為數字+id
`return post.id === +id;
檢查您的服務器端代碼是否在配置下方丟失。
const bodyParser = require("body-parser");
app.use(bodyParser.json({ limit: "50mb" }));
app.use(bodyParser.urlencoded({ extended: false }));
正文解析器允許您從您的路線中訪問 req.body
對於問題 1,
請嘗試添加此內容。
app.use(bodyParser.json());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.