【问题标题】:Get data from REST API nodeJS with Jquery [duplicate]使用 Jquery 从 REST API nodeJS 获取数据 [重复]
【发布时间】:2019-11-19 15:00:03
【问题描述】:

我有一个身份验证 API,当我发出登录请求时会响应令牌 (http://localhost:3001/api/users/login)。

//Login
router.post('/login', async (req, res) => {
    //Validate data before we use
    const { error } = loginValidation(req.body);
    if (error) return res.status(400).send(error.details[0].message)
    //Checking if the email exists
    const user = await User.findOne({
        email: req.body.email
    })
    if (!user) return res.status(400).send('Email or password dont match')
    //Password is correct 
    const validPass = await bcrypt.compare(req.body.password, user.password)
    if (!validPass) return res.status(400).send('Invalid password')

    //Create and assign a token

    const token = jwt.sign({ _id: user._id }, process.env.TOKEN_SECRET);
    res.header('auth-token', token).send(token)

})

我想使用 Jquery 从我前端的 const 令牌中获取本地存储中的数据。所以我注册了我的用户。

   $('#button-click').click(function () {
        $.ajax(
            {
                type: "POST",
                url: 'http://localhost:3001/api/user/register',
                data: JSON.stringify({
                    "name": $("#name").val(),
                    "email": $("#email").val(),
                    "password": $("#password").val()
                }),
                error: function (e) {
                    console.log(e)
                },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
            }

        )

    })

但我不知道如何获取这些数据,有人可以帮助我吗?

【问题讨论】:

    标签: jquery node.js rest api


    【解决方案1】:

    您可以像提供错误函数一样提供成功函数。请求成功时将调用此函数。

    $.ajax({
        ...,
        success: function(data, status, jqXHR) {
        //do stuff with data
        },
        ...
    });
    

    来源:https://api.jquery.com/jquery.ajax/

    【讨论】:

    • 所以,我的数据将存储在 function(data){ console.log(data.token) } 中?变量名是'token'
    • 在这种情况下,服务器端的变量名无关紧要。您发送的完整数据存储在数据中。你只发送令牌,所以数据就是你的令牌
    【解决方案2】:

    Success 用于处理来自 api 的响应

          $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "http://localhost:8080/api/user",
                    data: {},
                    contentType: "application/json; charset=utf-8",
                    dataType: "json", 
                    success: function (data, status, jqXHR) {
                        alert(data);
                        localStorage.setItem('token', data);
                    },
                    error: function (error) {
    
                        jsonValue = jQuery.parseJSON(error.responseText);
                        alert("error" + error.responseText);
                    }
                });
    

    更多详情-https://api.jquery.com/jQuery.ajax/

    有关本地存储的更多详细信息 - https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

    希望对你有帮助:)

    【讨论】:

    • @Vitor 更新了我对错误请求的回答,尝试添加 contentType 和数据类型。确保数据是json格式
    • 如果我想存储数据并注意提醒他怎么办?
    • 这取决于您想要存储数据的位置以及您想要执行的任何操作,您可以在成功函数 note、alert、store 等中执行该操作。该函数将在服务器响应成功后执行。我正在更改我的功能以将令牌存储在本地存储中以寻求帮助
    【解决方案3】:

    只需添加成功事件并将响应令牌存储在本地存储中并以您想要的方式使用令牌。

    $('#button-click').click(function () {
            $.ajax(
                {
                    type: "POST",
                    url: 'http://localhost:3001/api/user/register',
                    data: JSON.stringify({
                        "name": $("#name").val(),
                        "email": $("#email").val(),
                        "password": $("#password").val()
                    }),
                    error: function (e) {
                        console.log(e)
                    },
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
    
                    success: function(data, status, jqXHR) {
                           localStorage.setItem("app_token", data.token);
                    },
                }
    
            )
    
        })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-24
      • 2023-02-13
      • 2021-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多