【问题标题】:Expressjs Post-request is not getting recognized | 404-ErrorExpressjs Post-request 未得到认可 | 404-错误
【发布时间】:2020-10-21 07:25:24
【问题描述】:

我想在我的网站上实施贝宝,但我被困住了。总是当我尝试进行发布请求(也尝试使用邮递员)时,我没有得到只是正常的 404 错误页面的答案。控制台没有显示错误,所以我猜 post 请求没有被识别。

可能是什么问题,我该如何解决?

server.js

//payment
app.post("/pay", (req, res) => {
    // payment data
    const create_payment_json = {
        "intent": "sale",
        "payer": {
            "payment_method": "paypal"
        },
        "redirect_urls": {
            "return_url": "http://localhost:3000/success",
            "cancel_url": "http://localhost:3000/cancel"
        },
        "transactions": [{
            "item_list": {
                "items": [{
                    "name": "product1",
                    "sku": "001",
                    "price": "350.00",
                    "currency": "USD",
                    "quantity": 1
                }]
            },
            "amount": {
                "currency": "USD",
                "total": "350.00"
            },
            "description": "test"
        }]
    };
    
    // create payment
    paypal.payment.create(create_payment_json, (error, payment) => {
        if(error) {
            console.log("payment not successful");
            console.log(error)
        } else {
            console.log("payment successful");
            console.log(payment);
        }
    })
    
})

products.ejs

<form action="/pay" method="post">
    <input type="submit" value="add to cart" onclick="window.location.href='/pay'"/>
</form>

【问题讨论】:

  • 请从输入中删除onclick="window.location.href='/pay'"/,然后尝试
  • 它也不起作用:/
  • @silliton 在浏览器中(例如 firefox/chrome)你应该找到一个可以跟踪网络请求的地方,这可以方便地跟踪它 - 如果它在邮递员中不起作用,那么有些事情是奇怪的是请求而不是代码本身 - 仔细检查设置。

标签: javascript node.js express post http-status-code-404


【解决方案1】:

您需要确保的几件事

  1. 确保您将发布请求发送到正确的端口,以防您的快速服务器也没有托管实际站点。如果是,那么不要担心端口
  2. 可以使用js发送请求,防止页面刷新。
    const form = document.querySelector('form')
    form.addEventListener('submit', async function(e) {
      e.preventDefault()
      const port = 3000 //make sure this is the port your express erver is listening on
      const formData = new FormData(e.target)
      const itemId = formData.get('itemId')// You can store the items id in the name attribute of an input
      const response = await fetch(`http://localhost:${port}/pay`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({itemId})
      })
    })
    const data = await response.json()

    console.log(data)  // The response you would get from the server

【讨论】:

  • hm 这个代码对我不起作用,但感谢您的回答:)
  • 我刚刚连接到正常的 404 - 服务器未找到页面并且什么也没有发生
猜你喜欢
  • 1970-01-01
  • 2018-06-15
  • 1970-01-01
  • 2017-10-01
  • 2014-10-08
  • 2014-07-23
  • 2017-08-11
  • 1970-01-01
  • 2020-06-26
相关资源
最近更新 更多