【发布时间】:2020-01-23 07:32:06
【问题描述】:
我现在正在学习 MySQL,但遇到了一些问题。我试图向我的数据库发出发布请求::
我的客户端代码:
async function sendValues() {
const settings = {
method: 'post',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(product)
}
try {
const fetchResponse = await fetch('http://localhost:9001/products', settings);
const data = await fetchResponse.json();
console.log(data) // what the user send
} catch (err) {
return err
}
}
我的服务器端代码:
router.post('/', (req, res) => {
const { c_id, p_name, p_price } = req.body
const q =
`
INSERT INTO products (c_id,p_name,p_price)
VALUES("${c_id}", "${p_name}" , "${p_price}")
`;
con.query(q, (err, result, fields) => {
if (err) throw err;
res.json(result)
});
});
【问题讨论】:
-
首先,确保您可以在客户端和服务器之间建立正确的连接。然后就可以执行查询了。
标签: javascript mysql node.js reactjs express