问题
I want to send a axios put request into my backend but unauthorise error keeps coming out
Error:
PUT http://localhost:5000/api/items/unlike/5ef9e8176b04a67fe823bf5e/S 401 (Unauthorized)
On my put request, I attach my variable (clothes id and size) into the request url so i dont have request body. Here is my code.
Frontend:
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");
});
};
Backend:
// @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');
}
});
I have also enabled cors and when tried in postman everything works fine. The problem only comes when i tried in on the website itself
回答1:
An obvious reason for getting Unauthorized is either you are not sending token or your token is not valid. From your code first one is the case. If you see axios documentation , PUT method is defined like this:
axios.put(url[, data[, config]])
As you are not sending back data, axios assumes to get back data from 2nd parameter (which in your case is config). Try this:
axios.defaults.headers.common["x-auth-token"] = this.state.token;
Now you don't need to define any config. Simply send the HTTP request as:
axios.put('your_url').then() // handle your data here
回答2:
In the end, I just make an empty body and then send it together with the header and it works. I put this on the function
let data={}
axios.put(`url`,data,config).then(...)
来源:https://stackoverflow.com/questions/62659915/unauthorise-axios-put-request-without-data