【发布时间】:2021-11-29 19:19:53
【问题描述】:
在 axios 中有没有用GET 方法发送正文?因为在postman 中是可能的。我的后端代码如下:
我正在使用express.js + sequelize
const c_p_get_all = async (req, res) => {
const { category } = req.body;
const sql = `select p.id, p.p_image, p.p_name, p.p_desc, p.p_prize, p.p_size, c.c_name, cl.cl_name
from products as p
inner join collections as cl on cl.id = p.p_collection_id
inner join categories as c on c.id = cl.cl_category_id
where c.c_name = ?
order by p."createdAt" desc;`;
try {
const getData = await Product.sequelize.query(sql, {
replacements: [category],
});
if (getData[0] != "") {
res.status(200).send({
s: 1,
message: "success retrive all products",
data: getData[0],
});
} else {
res.status(404).send({
s: 0,
message: "data not found",
});
}
} catch (err) {
res.status(500).send({
message: err,
});
}
};
我的前端与react.js + axios
const test = "woman";
axios({
headers: {
"content-type": "application/json",
},
method: "GET",
url: "http://localhost:3001/api/v1/product",
data: { category: test },
})
.then((value) => console.log(value))
.catch((error) => console.log(error.response));
它总是转到status 404,但在postman 它的工作中,我试图搜索这个问题,但没有任何线索。那么有没有办法在 axios 中做到这一点,或者我应该将我的后端更改为POST 方法还是将req.body 更改为req.query?
【问题讨论】:
-
即使可以在 GET 请求中添加正文,这也是非标准的,通常是个坏主意。在我看来,最好将后端更改为 POST,或者只是在查询参数中发送数据(例如 localhost:3001/api/v1/product?category=test`)
-
@ippi 是的,我想我会通过使用查询参数来接受您的建议,因为我发现从 axios 文档中它不允许使用 GET 方法发送正文。感谢您的建议...