【问题标题】:GET request gives 404 error express js even though I have a well defined route in my express serverGET 请求会给出 404 错误 express js,即使我的 express 服务器中有明确定义的路由
【发布时间】:2021-07-24 14:33:13
【问题描述】:

我正在使用 Jquery 的 ajax 请求从服务器获取 JSON 对象,但是当调用该请求时,它会给出如下所示的 404 错误:

加载资源失败:服务器响应状态为 404(未找到)profile_data?uid=HW3gAHeiuJbQLMFQMbHA6nNlFUT2&_=1619880251360:1

就我而言,一切都是根据标准完成的,即 CRUD = Create:POST、Read:GET、Update:PUT 和 delete:DELETE。 请让我知道我的代码中的任何内容是错误的吗? 这是获取请求:

$(document).ready(()=>{
            $.ajax({
              url: '/profile_data',
              type: 'GET',
              cache: false,
              data: { "uid": uid},
              success: function(data){
                //Instantiate Variables of User Data
                

              }
              , error: function(jqXHR, textStatus, err){
                alert('text status '+textStatus+', err '+err)
              }
            });

          });

        } else {
          Window.locate.assign("/login");
        }
  });

这是服务器端代码:

app.get("/profile_data",   function (req, res){
    const current_user = req.body;
    const uid = current_user.uid;
    console.log(uid)
    db.ref("user_file_ref").on("value", snapshot=>{
        snapshot.forEach( dataSnapshot=>{
            if(uid === dataSnapshot.val().user_id){
                getFileFromNet(dataSnapshot.val().ipfs_ref).then( result =>{
                    const hash = JSON.parse(result);
                    let decrypted_string = decrypt(hash);
                    let return_data = JSON.parse(decrypted_string);
                    //console.log("Here!!")
                    res.send(return_data);
                }).catch(err =>{
                    console.log(err);
                });


            }
        })
    })
});

【问题讨论】:

  • 请求被调用时,请查看浏览器网络部分的请求URL。你可以吗?
  • 这是给我的网址
  • 你检查你的服务器了吗?运行了吗?
  • 是的,它正在运行

标签: jquery node.js ajax express http-status-code-404


【解决方案1】:

您应该使用 URL 传递参数。

像这样:

 $.ajax({
          url: '/profile_data/' + uid,
          type: 'GET',
          cache: false,
          // data: { "uid": uid}

在服务器端。

app.get("/profile_data/:uid",   function (req, res){
 const current_user = req.params.uid;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多