【发布时间】:2019-12-10 11:21:05
【问题描述】:
尝试将新数据添加到“recipes”表中。
console.log(data) 和 console.log(req.body) 为我提供了我输入并发送到后端的值,但它没有将其写入表和 chrome 控制台中的网络上我得到一个 PENDING状态
在后端 index.js__ 中创建配方
api.post('/recipe', passport.authenticate('jwt', {
session: false
}), (req, res) => {
const data = {
recipe_name: req.body.name,
recipe_meal: req.body.meal,
recipe_author: req.body.author,
recipe_description: req.body.description,
recipe_ingredients: req.body.ingredients,
recipe_preparation: req.body.preparation
}
console.log(req.body)
db.query('INSERT INTO recipes SET ?', [data], (err, results) => {
console.log(data)
if (err) {
res.status(500)
return;
}
db.query('SELECT * FROM recipes', (err, rows) => {
if (err) {
res.status(500)
return;
}
res.json({
recipes: rows
});
})
})
});
在前端 Profile.js__ 中创建配方
handleCreate(){
const jwt = localStorage.getItem('jwt')
console.log(jwt)
axios({
method: 'post',
data: {
name: this.state.name,
author: this.state.author,
meal: this.state.meal,
description: this.state.description,
ingredients: this.state.ingredients,
preparation: this.state.preparation
},
url: 'http://localhost:4000/api/recipe',
headers: {
'Authorization': 'Bearer ' + jwt
}
}).then((response) => {
this.setState({ recipe: response.data });
console.log(this)
}).catch((error, res) => {
if(error.response.status === 401) {
console.log("Error:", error);
alert("Failed")
}
})
}
输入字段示例:
<TextField helperText="Enter the name of your recipe" label="name" onChange = {(event) => this.setState({name: event.target.value})}/>
<Button color="secondary" onClick={(event) => this.handleCreate(event)}>Submit Recipe</Button>
【问题讨论】:
标签: reactjs express jwt axios passport.js