首页 > 解决方案 > 如何使用 csrf 和 body 进行 ajax 调用?

问题描述

我已经用 django 构建了一个登录 api。我用邮递员检查了它的功能。请求正文是

{"user":{"email":"surendersingh1995nov@gmail.com", "password":"Singo*1995"}}

请求网址是

 POST 127.0.0.1:8000/api/users/login/

标头是内容类型

application/json

回应是

{
    "user": {
        "email": "surendersingh1995nov@gmail.com",
        "username": "ArjunSingh",
        "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwiZXhwIjoxNjAwMjM3MjcxfQ.OBF3tg2YmXC4hl4D7eTfx38rrXX9RKGwIQBqKorwqOw"
    }
}

这是我希望在 ajax 调用中获得响应的方式。API 在 Postman 中运行良好。但是,如果我尝试通过 AJAX 发出相同的请求,我会收到 400 Bad request 错误。

我进行的 AJAX 调用

$.ajax({
            url: "/api/users/login/?",
            method: "POST",
            contentType: "application/json",
            data:{"user":{"email":"surendersingh1995nov@gmail.com", "password":"Singo*1995"}},
            success: function (data) {
                console.log(data)
            },
            error: function (data) {
              console.log("error")
              console.log(data.statusText)
              console.log(data.status)
            }
          })

标签: jquerydjangoajaxformsapi

解决方案


推荐阅读