2017-11-09 1 views
1

연습을 위해 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> 
) 
} 

}

수출 기본 응용 프로그램;

+0

POST 메서드를 고려할 때 서버 쪽이 리다이렉트로 끝나고 결과 값 (새롭게 생성 된 데이터 객체를 포함 할 가능성이 있음)을 사용하지 않는다는 점을 고려하면 놀랍습니다. 값이 데이터베이스에 기록되는 것을 보시겠습니까? – Jaxx

+0

값이 추가되지 않습니다. 각각의 객체는'''{ "_id": "5a0472c56f37cb06a4c8f54c"} "''와 같은 ID 만 포함합니다. – aaayumi

+0

하지만, 당신이 레시피를 추가 할 때마다,'_id' 필드가 설정된'recipe' 컬렉션에 새로운 항목이 있습니다. 옳은? – Jaxx

답변

0

서버 측 변경 :

app.post('/recipe', (req, res) => { 
    // log the body of the request, to make sure data is properly passed 
    console.log(req.body); 
    // use mongodb's insertOne instead of the deprecated save 
    db.collection('recipe').insertOne(req.body, (err, result) => { 
    if (err) return console.log(err); 
    // log the result of db insertion 
    console.log(result); 
    console.log('saved to database'); 
    // send the freshly saved record back to the front-end 
    res.json(result); 
    }); 
}); 

프런트 엔드 변경 :

class App extends Component { 
    constructor(props){ 
    super(props); 
    // add state to hold recipe returned from POST call 
    this.state = { 
     recipe: null, 
     name: '', 
     ingredients: '', 
     descriptions: '' 
    }; 
    this.handleSubmit = this.handleSubmit.bind(this); 
    } 

    handleSubmit(e) { 
    e.preventDefault(); 
    const { name, ingredients, descriptions } = this.state; 
    fetch('/recipe', { 
     method: 'POST', 
     body: JSON.stringify({ 
     name, 
     ingredients, 
     descriptions 
     }), 
     headers: {"Content-Type" : "application/json"} 
    }) 
    // when call completes, it should return the newly created recipe object 
    // as it was saved in the DB - just store it into state 
    .then((recipe)=> { 
     this.setState({recipe}); 
    }); 
    // TODO: handle error case 
    } 

    render() { 
    // added a paragraph tag to display the ID of the freshly created recipe 
    // it's only displayed if recipe is not null or undefined 
    // further changes: turning inputs into controlled inputs 
    const { name, ingredients, descriptions } = this.state; 
    return (
     <div className="App"> 
     <h1>Recipe List</h1> 
     <form onSubmit={this.handleSubmit}> 
      <input 
      value={name} 
      type="text" 
      onChange={e => this.setState({ name: e.target.value })} 
      placeholder="name" /> 
      <input 
      value={ingredients} 
      type="text" 
      onChange={e => this.setState({ ingredients: e.target.value })}     
      placeholder="ingredients" /> 
      <input 
      value={descriptions} 
      type="text" 
      onChange={e => this.setState({ descriptions: e.target.value })} 
      placeholder="descriptions" /> 
      <input type="submit"/> 
      { recipe && 
      <p>Saved ID: {this.state.recipe._id}</p> 
      } 
     </form> 
     </div> 
    ); 
    } 
} 

export default App; 

또한 변경 : 제어 입력에 세 텍스트 입력을 온 (3 개 필드의 값은 상태 추적, 양식을 제출하면 fetch으로 전달됩니다.

+0

답변 해 주셔서 감사합니다. 나는 그것을 시도했지만 _id로부터 어떤 데이터도 추가하지 않았다. 터미널 결과'CommandResult { 결과 : {N : 1 opTime {TS : [대상] t : 2} electionId : 7fffffff0000000000000002, OK : 1} 연결 : 연결 { 도메인 : 널 (null), _events : {오류 : [오브젝트], 가까운 : [오브젝트], 제한 시간 : [오브젝트], 가 parseError : [개체]}는 ..... ' – aaayumi

+0

출력 무엇 @aaayumi (app.post ('/ recipe', ...)'의 시작 부분에서)'console.log (req.body)'의? – Jaxx

+0

답장을 보내 주셔서 감사합니다.그것은 빈 객체를'{} '출력합니다 .. – aaayumi

관련 문제