0

I have attempted to create a request in javascript, that has previously worked using python just fine.

the following is an accurate representation of the code I used to post the request with python:


url = 'https://website.com/api/e1'
    
header = {
   'authorization': 'abcd1234'
}
payload = {
    'content': "text",
}
r = requests.post(url, data=payload,headers=header )

This (above) works just fine in python.

now what I did in javascript is the following:

payload = {
    "content": "this is text",
  };
  fetch("https://website.com/api/e1", {
    method: "POST",
    headers: {
      "authorization":
        "abcd1234",
    },
    body: JSON.stringify(payload),
  });

but this is returning the error 400- Bad request

2 Answers 2

1

When using data parameters on python requests.post, the default Content-Type is application/x-www-form-urlencoded(I couldn't find it on the document, but I checked the request. If you know, please leave a comment).

To achieve the same result with fetch, you must do as follows.

const payload = {
  'content': 'this is text',
};
fetch('https://website.com/api/e1', {
  method: 'POST',
  headers: {
    'authorization': 'abcd1234',
  },
  body: new URLSearchParams(payload),
});
Sign up to request clarification or add additional context in comments.

1 Comment

Works flawlessly. appreciate it!
1

You don't need to do this body: JSON.stringify(payload), rather you can simply pass payload in body like this body:payload

1 Comment

Thanks, but that unfortunately does not help in fixing the error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.