【问题标题】:Why i get error when try post request with headers?为什么在尝试使用标头发布请求时出现错误?
【发布时间】:2018-12-30 07:04:07
【问题描述】:

我在网上商店创建商品订单,但是当我发出 POST 请求时

addToCart: function () {
      axios.post('http://localhost:8081/orders/',{
        quantity: '1',
        product: this.id,
        user: this.$store.getters.getUser._id
      },{
        headers: {
          Authorization:"Bearer " + this.$store.getters.getToken
        }
      })
      .then(res => {
        console.log('sucsecc')
      })
      .catch(err => {
        console.log(err)
      })
    }

这里是jsx代码

<div class="descCont"><button class="add" @click="addToCart">Add to Cart</button></div>

我错了:

POST localhost:8081/orders 404 (Not Found)
Error: Request failed with status code 404
at createError (createError.js?16d0:16)
at settle (settle.js?db52:18)
at XMLHttpRequest.handleLoad (xhr.js?ec6c:77)

我检查了正文中传入数据的正确性,一切正常 在那里正确。你能告诉我我做错了什么吗? Node.js(orders.js) 上的服务器代码

router.post('/',checkAuth,upload.single('productImge'), (req, res, next) => {
    Product.findById(req.body.productId)
        .then(product => {
            if (!product){
                return res.status(404).json({
                    message: 'Product not found'
                })
            }
            const order = new Order({
                _id: mongoose.Types.ObjectId(),
                quantity: req.body.quantity,
                product: req.body.productId,
                user: req.body.user
            })
            return order.save()
        })
        .then(result => {
            res.status(201).json({
                message: 'Order stored',
                createdOrder: result

            })
        })
        .catch(err => {
            console.log(err)
            res.status(500).json({
                error: err
            })
        })
})

在主文件中:

const ordersRoutes = require('./routes/orders')

【问题讨论】:

  • 您确定服务器在 8081 端口上运行吗?它是正确的端点 URL 吗?你有代理/防火墙吗?
  • 获取请求工作!但是post return err.
  • 发布路线的路径中没有“订单”,或者您没有包含此代码?
  • 我在 PostMan 和所有作品中测试。
  • 您的 Postman 测试是否还包括请求 url 中的尾部斜杠?

标签: javascript node.js vue.js axios


【解决方案1】:

也许您发布的产品 ID 错误?在您的第一个语句中,您的第一个 if 语句将返回 404 错误。

请注意product: this.id, 可能是undefined

【讨论】:

    猜你喜欢
    • 2019-09-05
    • 1970-01-01
    • 2019-10-10
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 2018-10-03
    • 2015-05-29
    相关资源
    最近更新 更多