我是React js和node js的新手。这是一个简单的问题,但我不知道如何解决它。我使用轻量级的fetch来发布数据并从bodyparser接收数据。但是它总是未定义的 form.js
import React from 'react';
import Fetch from 'whatwg-fetch';
class Form extends React.Component{
constructor(props){
super(props);
this.state = {
value:'',
posted:''
}
}
onPost(e){
e.preventDefault();
// console.log(this.refs.email.value);
// console.log(this.refs.name.value);
if(this.refs.email.value && this.refs.name.value != ''){
fetch('/post',{
method:'POST',
body:JSON.stringify({
email:this.refs.email.value,
name:this.refs.name.value
})
})
}
}
render(){
console.log(this.state);
return (
<div>
<form className="postform" onSubmit={this.onPost.bind(this)}>
<label>Email Addres</label>
<input type="email" ref="email" className="form-control"/>
<label>Name</label>
<input type="text" ref="name" className="form-control"/>
<br/>
<br/>
<button type="submit" className="btn btn-primary">Post To server</button>
</form>
</div>
)
}
}
export default Form;
server.js
import express from 'express';
import bodyParser from 'body-parser';
const app = express();
const jsonParser = bodyParser.json();
app.set('view engine','ejs');
app.use(express.static('./public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('*',(req,res)=>{
res.render('index')
});
app.post('/post',(req,res)=>{
console.log(req.body);//undefines
res.send('Ok ')
});
app.listen(3000,err=>{
if(err) throw err;
console.log('Im In at 3000')
});
答案 0 :(得分:0)
试试这个:
替换
app.use(bodyParser.urlencoded({ extended: false }));
带
app.use(bodyParser.urlencoded());
OR
app.use(bodyParser.urlencoded({ extended: true }));