Implement curl post request in JavaScript Fetch API

I’m trying to implement this post request using curl in the JS Fetch API:

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.

I tried this, but it doesn’t work. I get a 401 unauthorized error back from the server.

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!

Edited code with auth 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.

144 thoughts on “Implement curl post request in JavaScript Fetch API”

  1. hey there and thank you for your information – I
    have definitely picked up anything new from right here.
    I did however expertise some technical issues using this site,
    since I experienced to reload the site lots of times previous to I could get it to load properly.
    I had been wondering if your web hosting is OK?
    Not that I’m complaining, but slow loading instances times will very frequently affect your placement
    in google and can damage your high-quality score
    if ads and marketing with Adwords. Anyway I am adding this RSS
    to my e-mail and can look out for much more of your respective exciting
    content. Make sure you update this again soon. http://antiibioticsland.com/Tetracycline.htm

    Reply
  2. [url=http://cialisgenr.com/]canada cialis generic[/url] [url=http://ivermectinzf.com/]stromectol online[/url] [url=http://tadalafilzm.com/]tadalafil over the counter[/url] [url=http://zipimeds.com/]2 trazodone[/url] [url=http://fluoxetineantidepressant.com/]fluoxetine 40 mg capsule price[/url] [url=http://buyivermectinmedicine.com/]ivermectin buy online[/url] [url=http://cialistabsonline.com/]tadalafil pills[/url] [url=http://sildenafilbuyf.com/]how much is sildenafil 20 mg[/url] [url=http://sildenafilcpill.com/]sildenafil pills online[/url] [url=http://cialisepills.com/]cialis 20 mg india[/url]

    Reply

Leave a Comment