未经数据授权未经授权的axios放置请求 [英] Unauthorise axios put request without data

查看:104
本文介绍了未经数据授权未经授权的axios放置请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将axios放置请求发送到后端,但是未授权错误不断出现

I want to send a axios put request into my backend but unauthorise error keeps coming out

错误:

PUT http://localhost:5000/api/items/unlike/5ef9e8176b04a67fe823bf5e/S 401 (Unauthorized)

在我的put请求中,我将变量(衣服id和大小)附加到请求url中,所以我没有请求正文.这是我的代码.

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.

前端:

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,在邮递员中尝试使用时一切正常.仅当我在网站上尝试过时,问题才会出现

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

推荐答案

获得未授权的明显原因是您未发送令牌或令牌无效.从您的代码来看,第一种情况就是如此.如果您看到axios文档,则PUT方法的定义如下:

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]])

由于您没有发送回数据,因此axios假定从第二个参数(在您的情况下为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;

现在,您无需定义任何配置.只需将HTTP请求发送为:

Now you don't need to define any config. Simply send the HTTP request as:

axios.put('your_url').then() // handle your data here

这篇关于未经数据授权未经授权的axios放置请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆