Issue
Having a huge issue I came across in sending a POST request using Fetch to get a URL shortened.
I am good and able to do a POST request by cURL command to this url shortener API:
Curl command
curl -d 'api_key=xxxxxxxxxxxxxx&url=https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch' http://fakeurlforexample/api/shorten/
Response
{"url": "https://fakeurlforexample/BdzfM3", "long_url": "https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch", "name": "BdzfM3"}
And I get this great response payload from the API.
But when I do this by Fetch with this code I provided below, I get a 200 OK and in the response payload I have a 400 validation error that I am missing the API key.
However, the request payload in the developer console shows that the parameters were passed on properly to the API (I think...)
{"api_key":"xxxxxxxxxxxxxxxxx","url":"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch"}
Here is my code:
let get_url = 'http://fakeurlforexample.com/api/shorten/';
let request = new Request(get_url, {
method: 'POST',
body: JSON.stringify({'api_key':'xxxxxxxxx', 'url': 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch'})
});
fetch(request)
.then(function() {
console.log(request);
console.log(request.url);
})
Does anyone see the mistake I am making here?
Been beaten down by this for across hours upon hours this week now. Thanks for any help and assistance! And no, I can't easily transition the code to axios as it is right now. This is a demonstration so I'm really just trying to get it to work.
Solution
From the curl manpage Options section on -d, --data <data>
:
(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded. Compare to -F, --form.
Whereas with your request, you are sending a JSON object (Content Type: application/json
):
let request = new Request(get_url, {
method: 'POST',
body: JSON.stringify({'api_key':'xxxxxxxxx', 'url': 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch'})
});
Since you know the API endpoint accepts application/x-www-form-urlencoded
because the curl request succeeds, you can set the content type as application/x-www-form-urlencoded
and send the body as a string:
let request = new Request(get_url, {
method: 'POST',
headers: new Headers({'content-type': 'application/x-www-form-urlencoded'}),
body: 'api_key=xxxxxxxxxxxxxx&url=https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch'
});
Answered By - Daniel Bank Answer Checked By - Mary Flores (WPSolving Volunteer)