简体   繁体   English

在 JavaScript 中实现 curl 发布请求 Fetch API

[英]Implement curl post request in JavaScript Fetch API

I'm trying to implement this post request using curl in the JS Fetch API:我正在尝试在 JS Fetch API 中使用 curl 来实现这个发布请求:

curl --user apikey:{my_secret_apikey} --request POST --header "Content-Type: application/json" --data "{\"text\":[\"Hello\"],\"model_id\":\"en-es\"}" "{my_secret_url}/v3/translate?version=2018-05-01"

I'm having trouble implementing the API key.我在实现 API 密钥时遇到问题。

I tried this, but it doesn't work.我试过这个,但它不起作用。 I get a 401 unauthorized error back from the server.我从服务器收到 401 未经授权的错误。

fetch(url, {
    method: "POST",
    headers: { 'Content-Type': 'application/json' },
    user: {
        "apikey": blablabla_api_key
    }
    body: {
        "text": [term],
        "model_id": "en-hi"
    }
}).then(res ........

Any help is appreciated!任何帮助表示赞赏!

edit: if you have any other suggestion as to how to implement this post request into JS using some other HTTP library, that helpful too!编辑:如果您对如何使用其他一些 HTTP 库将这个帖子请求实现到 JS 有任何其他建议,那也很有帮助!

Edited code with auth header:使用授权 header 编辑的代码:

let headers = new Headers();

headers.append('Authorization', 'Basic ' + btoa("apikey" + ":" + "my_api_key"));
headers.append('Content-Type', 'application/json');
fetch(url, {
    method: "POST",
    headers: headers,
    body: {
        "text": ["Hello"],
        "model_id": "en-es"
    }
}).then(result => {
    console.log(result);
    resolve(result.translations[0].translation);
}).catch(err => console.log(err));

This results in a 400 Bad Request error, even though the curl request works fine.这会导致 400 Bad Request 错误,即使 curl 请求工作正常。

hopefully, I am not too late with answering your question.希望我回答你的问题还为时不晚。 I encountered the same problem as you did and my solution was to encode the authorization into base64.我遇到了和你一样的问题,我的解决方案是将授权编码为 base64。

https://observablehq.com/@mbostock/fetch-with-basic-auth#:~:text=To%20use%20basic%20authentication%20with,result%20in%20a%20401%20error . https://observablehq.com/@mbostock/fetch-with-basic-auth#:~:text=To%20use%20basic%20authentication%20with,result%20in%20a%20401%20error

I am using Node.js, so I needed to use a Buffer for the encoding process.我正在使用 Node.js,所以我需要使用 Buffer 进行编码过程。 If I understood your problem correctly, you'd have to do the following:如果我正确理解了您的问题,您必须执行以下操作:

let buffer = Buffer.from(apikey:{my_secret_apikey})
let base64data = buff.toString('base64')

Your authorization header should then be set to something like this:您的授权 header 应设置为如下所示:

headers: {'Authorization': `Basic ${base64data}`}

This helped me a to solve at least the problem I was struggling with.这至少帮助我解决了我一直在努力解决的问题。 Hope it works for you as well!希望它也适用于你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM