【问题标题】:how to use post method in nodejs?如何在nodejs中使用post方法?
【发布时间】:2021-08-29 20:39:22
【问题描述】:

我在 nodejs 中使用 post 方法

好吧,当我使用邮递员运行它时它工作正常

但是当我在浏览器中运行它时,它会显示错误

Cannot GET /listUserslistUsers:1 GET http://localhost:8081/listUsers 404 (Not Found) 这个

这是我的节点 js 代码

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.post('/listUsers', function (req, res) {
        var f = parseInt(req.body.f);
    console.log("hello" + f);
   var l = parseInt(req.body.l);
    var sum = Number(f + l);
    res.send('The sum is: ' + Number(sum));
})
var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port
   console.log("Example app listening at http://%s:%s", host, port)
})

这是我发送数据的 jquery 代码

usid();
function usid(med){
  var f = "my new name";
  $.ajax({
    crossDomain: true,
    url:"http://localhost:8081/listUsers",
    method:"POST",
    data:{med,f:f},
    success:function(data,status){
      console.log("send");
    }
  })
}

我能找到我做错的地方吗?

【问题讨论】:

  • 您只能使用浏览器发送 GET 请求。
  • 对于测试 post, delete, put or patch 使用 cuRLpostman
  • 这是Example
  • 但在 get 方法中我无法发送数据,我正在使用 webrtc,我正在通过 ajax 将 nodejs 与 php 连接起来,所以我必须从我的 nodejs 发送和接收数据,所以如果我不能使用 post 那么可以你建议我在浏览器中传递或接收数据的任何其他 http 方法?@murat colyaran,@sefa
  • 您在 listUsers 中发送什么数据?在您的代码中看不到任何内容。检查查询参数如何使用 GET 发送一些数据。

标签: node.js express post node-modules body-parser


【解决方案1】:

您没有提交任何表单/存储任何资源。理想情况下,您尝试的操作应该使用 GET 完成。

浏览器无法使用的原因: 通过更改 url 访问页面是一种 GET 方法。您没有在您的应用程序中为此路由定义 GET 方法。只有一种 POST 方法。

你可以做什么: 在服务器和 AJAX 中将 POST 更改为 GET。相应地更改这两种方法。然后你必须通过query params(谷歌一些东西,问号后面的一切都是查询参数的工作方式)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 2021-12-05
    • 1970-01-01
    相关资源
    最近更新 更多