연습을 위해 React-Node.js 응용 프로그램을 만들려고합니다. POST 요청을 보내는 중 문제가 발생했습니다. App.js에서 POST 요청을 가져 오면 ID 만 반환합니다. 나는 그것이 3 개의 값을 더 반환 할 것으로 예상했다.POST POST가 Express API 서버에서 _id 객체 만 반환합니다. React FrontEnd
현재 객체
{ _id: 5a046d52bb5d37063b3c8b21 }
내가 제대로 req.body 값을 추가하는 방법에 적합 객체
{_id: "59e9fed60fe8bf0d7fd4ac6e", name: "recipe1", ingredients: "apple", descriptions: "cut an apple"}
? 나는이 솔루션을 Post an object with fetch using react js and express API server라고했지만 내 앱에서는 작동하지 않았다.
하는 index.js (Node.js를)
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
// Serve static files from the React app
app.use(express.static(path.join(__dirname, 'client/build')));
app.use(bodyParser.urlencoded({ extended: true}));
var db
const MongoClient = require('mongodb').MongoClient
MongoClient.connect
('mongodb://Recipe:[email protected]:25914/ayumi', (err, database) => {
if (err) return console.log(err)
db = database
app.listen(8080,() => {
console.log('listening on 8080')
})
})
app.get('/api', (req,res)=> {
db.collection('recipe').find().toArray((err, results) => {
if(err) return console.log("no recipe");
res.json(results);
})
})
app.post('/recipe', (req,res)=>{
db.collection('recipe').save(req.body, (err, result) => {
if(err) return console.log(err);
console.log(req.body)
console.log('save to database');
res.redirect('/');
})
})
App.js이 (반응)
class App extends Component {
constructor(props){
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e){
e.preventDefault();
fetch('/recipe', {
method: 'POST',
body: JSON.stringify({
name: this.refs.name.value,
ingredients: this.refs.ingredients.value,
descriptions: this.refs.descriptions.value
}),
headers: {"Content-Type" : "application/json"}
})
.then((res)=> {
return res.json()
})
.then((body)=>{
console.log("body" + body)
console.log("result" + this.refs.name.value)
})
}
render() {
return (
<div className="App">
<h1>Recipe List</h1>
<form onSubmit={this.handleSubmit}>
<input type="text" placeholder="name" ref="name" />
<input type="text" placeholder="ingredients" ref="ingredients" />
<input type="text" placeholder="descriptions" ref="descriptions" />
<input type="submit"/>
</form>
</div>
)
}
}
수출 기본 응용 프로그램;
POST 메서드를 고려할 때 서버 쪽이 리다이렉트로 끝나고 결과 값 (새롭게 생성 된 데이터 객체를 포함 할 가능성이 있음)을 사용하지 않는다는 점을 고려하면 놀랍습니다. 값이 데이터베이스에 기록되는 것을 보시겠습니까? – Jaxx
값이 추가되지 않습니다. 각각의 객체는'''{ "_id": "5a0472c56f37cb06a4c8f54c"} "''와 같은 ID 만 포함합니다. – aaayumi
하지만, 당신이 레시피를 추가 할 때마다,'_id' 필드가 설정된'recipe' 컬렉션에 새로운 항목이 있습니다. 옳은? – Jaxx