在Javascript fetch中转换python请求?

我想知道如何在 javascript 中编写这个 python 请求:


url = "something.something"

data = {"name":"description"}

auth = ("user","11111")


x = requests.post(url, json=data, auth=auth)

到目前为止我有这个:


fetch(`something.something`, {

      method: 'POST',

      header: {

        'Content-Type': 'application/json',

        'Authorization': 'user:11111',

      },

      body: {

        "name": "description"

      }

})

但是我有一个403。我的猜测是授权格式不正确。


慕丝7291255
浏览 113回答 1
1回答

饮歌长啸

auth = ("user","11111")x = requests.post(url, json=data, auth=auth)这HTTPBasicAuth用于授权。基本 HTTP Auth要求在Authorization标头中传递凭据,如下所示:Authorization: Basic <base64(user:password)>所以 javascript 示例应该类似于:fetch(`something.something`, {&nbsp; &nbsp; &nbsp; method: 'POST',&nbsp; &nbsp; &nbsp; header: {&nbsp; &nbsp; &nbsp; &nbsp; 'Content-Type': 'application/json',&nbsp; &nbsp; &nbsp; &nbsp; 'Authorization': 'Basic ' + btoa('user:11111'),&nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; body: {&nbsp; &nbsp; &nbsp; &nbsp; "name": "description"&nbsp; &nbsp; &nbsp; }})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript