【发布时间】:2020-08-21 00:32:24
【问题描述】:
我的数据库中有一个名为 products 的表,我正在尝试使用 node.js express 服务器作为 Web 服务并将 react.js 作为前端语言插入。
下面是我用来执行插入的 react.js 表单。
function App() {
return (
<div className="container">
<form onSubmit = {(e) => Add(e)}>
<div className="form-group">
<label htmlFor="examplePname">Name</label>
<input type="text" className="form-control" id="examplePname" aria-describedby=""/>
</div>
<div className="form-group">
<label htmlFor="examplePprice">Price</label>
<input type="number" className="form-control" id="examplePprice"/>
</div>
<div className="form-group form-check">
<input type="checkbox" className="form-check-input" id="exampleCheck1"/>
<label className="form-check-label" htmlFor="exampleCheck1">Check me out</label>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
);
}
function Add(e){
e.preventDefault();
let request = {
name: document.getElementById('examplePname').value,
price: document.getElementById('examplePprice').value,
}
alert("returns this:"+ request)
axios.post('http://localhost:3000/add', request)
.then(resp => {
alert(resp.data.message);
})
.catch(err => {
console.log(err);
})
}
下面是我的node.js express Webservice
router.post('/add', (req, res) => {
const {name, price} = req.query;
console.log(name, price); ///Do this before you write the insert query
//res.send('adding product');Do this before you write the insert query (add temp products to view in cmd)
const INSERT_QUERY = `INSERT INTO products (name, price) VALUES('${name}', ${price})`; //after do an insert query to add to db proper
connection.query(INSERT_QUERY, (err, results) => {
if (err) {
return res.send({
message: "failed"
})
} else {
return res.send({
message: "successful"
});
}
});
});
但是当我插入时,我在 console.log 中得到了 name 和 price 的未定义值。
【问题讨论】: