我想将axios put请求发送到后端,但是未授权错误不断出现
错误:
PUT http://localhost:5000/api/items/unlike/5ef9e8176b04a67fe823bf5e/S 401 (Unauthorized)
在我的put请求中,我将变量(衣服id和大小)附加到请求url中,所以我没有请求正文。这是我的代码。
前端:
toCart = () => {
let self = this;
let config = {
headers: {
"Content-Type": "application/json",
"x-auth-token": this.state.token,
},
};
// config = JSON.stringify(config);
console.log(this.props);
axios
.put(
`http://localhost:5000/api/items/wishlist/cart/${this.props.item.item}/${this.props.item.size}`,
config
)
.then((res) => {
console.log(res.data);
self.setState({
item: res.data,
});
})
.catch((err) => {
console.error(err);
alert("Edit fail");
});
};
后端:
// @route PUT api/items/wishlist/cart/:item_id/:size
// @desc Transfer item from wishlist to shopping cart
// @access Private
router.put('/wishlist/cart/:item_id/:size', auth, async (req, res) => {
try {
const buyer = await Buyer.findOne({
_id: req.user.id,
});
if (!buyer) {
return res.status(404).json({ msg: 'User not found' });
}
let itemFound = false;
for (var i = 0; i < buyer.wishlist.length; i++) {
if (
buyer.wishlist[i].item.toString() === req.params.item_id &&
buyer.wishlist[i].size === req.params.size
) {
buyer.cart.push({
item: buyer.wishlist[i].item,
brand: buyer.wishlist[i].brand,
title: buyer.wishlist[i].title,
price: buyer.wishlist[i].price,
size: buyer.wishlist[i].size,
image: buyer.wishlist[i].image,
quantity: 1,
});
buyer.wishlist.splice(i, 1);
itemFound = true;
}
}
await buyer.save();
itemFound
? res.json(buyer.cart)
: res.status(404).json({ msg: 'Item not found' });
} catch (err) {
console.log(err.message);
if (err.kind == 'ObjectId') {
return res.status(400).json({ msg: 'Item not found' });
}
res.status(500).send('Server error');
}
});
我还启用了cors,并且在邮递员中尝试使用时一切正常。仅当我在网站上尝试过时,问题才会出现
答案 0 :(得分:2)
获得未授权的明显原因是您没有发送令牌或令牌无效。从您的代码来看,第一种情况就是如此。 如果您看到axios文档,则PUT方法的定义如下:
axios.put(url[, data[, config]])
由于您没有发送回数据,因此axios假定从第二个参数(在您的情况下为config)中获取数据。 试试这个:
axios.defaults.headers.common["x-auth-token"] = this.state.token;
现在,您无需定义任何配置。只需将HTTP请求发送为:
axios.put('your_url').then() // handle your data here
答案 1 :(得分:0)
最后,我只是制作一个空的正文,然后将其与标题一起发送,并且可以正常工作。我把它放在函数上
let data={}
axios.put(`url`,data,config).then(...)