I am having trouble making a simple POST Request [duplicate] - javascript

This question already has answers here:
Empty body in fetch POST request
(5 answers)
Trying to use fetch and pass in mode: no-cors
(9 answers)
Closed 3 months ago.
I am trying to do a simple call to an API endpoint using the following code and keep getting the following error:
POST net::ERR_ABORTED 400 (Bad Request)
SyntaxError: Unexpected end of input
The request options
const requestOptions = {
method: 'POST',
mode: 'no-cors',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: email,
password: password
})
};
The fetch request
await fetch("https://dev.rapptrlabs.com/Tests/scripts/user-login.php", requestOptions)
.then(async response => await response.text())
.then(response => response === "" ? {} : JSON.parse(response) )
.catch(e => {
console.log(e)
})
I am not sure what I am doing wrong.
Edit: I was only provided with the following documentation:
a. When the form has been successfully submitted passing all
validation errors, call the following API:
http://dev.rapptrlabs.com/Tests/scripts/user-login.php i. This API
endpoint needs to be called with a POST request. ii. It takes two body
params: email and password. iii. For testing purposes, use the
following email and password: test#rapptrlabs.com / Test123. iv. A
successful response will look like the following:
{ "user_id": 16,
"user_email": "test#rapptrlabs.com",
"user_username": "testuser",
"user_is_active": 1,
"user_profile_image": "http://dev.rapptrlabs.com/Tests/images/taylor_avatar.png",
"user_last_active_epoch": 1544680026,
"user_creation_epoch": 1544713200,
"user_is_new": 1,
"user_token": "6dd4737a8b7ec61313ae5e900420d46815e1d13b2902be71b97a8fbf1f421a3e" }
Edit: This issue is resolved now. The issue was that I had to use a form tag to submit the fetch request. And I have to use FormData as the request option of the fetch request.

Related

How can I send data on request.body in an ajax call? [duplicate]

I have a React application where I am changing POST method to GET with the request body as it is. It works fine with POST request however when I change the method to GET, it gives me error-
message: "org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public
My Front End Code-
export const setData = (getData) => dispatch => {
axios({
method: 'GET',
url: 'http://localhost:8080/api',
headers: {
'Content-Type': 'application/json'
},
data: getData
})
.then (response => {
dispatch({
type: API_DATA,
payload: response.data
})
dispatch({
type: SET_SEARCH_LOADER,
payload: false
})
})
.catch(function(error) {
})
}
Can someone let me know what I am missing here. As per my understanding, http allows to have a request body for GET method.
As per my understanding, http allows to have a request body for GET method.
While this is technically true (although it may be more accurate to say that it just doesn't explicitly disallow it), it's a very odd thing to do, and most systems do not expect GET requests to have bodies.
Consequently, plenty of libraries will not handle this.
The documentation for Axois says:
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
Under the hood, if you run Axios client side in a web browser, it will use XMLHttpRequest. If you look at the specification for that it says:
client . send([body = null])
Initiates the request. The body argument provides the request body, if any, and is ignored if the request method is GET or HEAD.
If you want to send parameters with get request in axios, you should send parameters as params.
If you want to set "Content-type":"application/json" and send params with get request, you should also send an empty data object.
For example:
const AUTH_TOKEN = 'Bearer token'
const config = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': AUTH_TOKEN,
},
data: {},
params: {
"post_id": 1
}
}
axios.get("http://localhost/api/v1/posts/", config)
This is not axios, the error origniates from the java backend you're talking to. The public field in your request body is missing.
If you just want to send the data as parameters (which would be odd), pass it using params instead of data (as shown here: https://github.com/axios/axios#example).
I personally don't think your API should support GET with a request body (talk to the devs and ask for documentation).

How to use AXIOS to POST to a .php url endpoint in reactJS? [duplicate]

This question already has answers here:
Why is an OPTIONS request sent and can I disable it?
(15 answers)
Closed 1 year ago.
Running into a bad request 400 error when using axios call to endpoint ending in .php.
Code for the call looks like this
const API = {
userLogin: function () {
const email = "test#email";
const password = "Test1234";
return axios({
method: "POST",
body: {
email,
password,
},
headers: {
"Content-Type": "application/json",
},
url: "url ends in /user-login.php",
});
},
};
the email and password are different in my actual code as are is the URL, but they were giving to me as body params to pass to the endpoint. The instructions state to make the API call method "POST" and pass email and password as body params.
here is the error response i get in the picture included.
the top error is with using Fetch, and the Error that is expanded is with that axios call above. Any suggestions?
Check the Axios documentation, https://github.com/axios/axios#request-config
You probably want to put the variables you have in the body section in your code as data instead, i.e.
data: {
email,
password,
},

How to avoid the CORS error without telling fetch "mode: "no-cors"? [duplicate]

This question already has answers here:
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 3 years ago.
My initial question (JavaScript fetch API data and use XML response as an object) was marked a duplicate of SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data using fetch, so I am asking another question, building on top of what I learned (or assume):
I have a cors error when using fetch() in JS to call an API if I don't define "{ mode: "no-cors" }". I also get the error when I run a local server! When I do define no-cors, I don't get the cors error, but the response seems to be empty.
How to avoid the cors error and get a response?
My code is the following:
async function apiCall() {
const url =
"https://service.runmyaccounts.com/api/latest/clients/apitest/invoices?api_key=d1bvbxkI8f1bnMBJ4sZiC-xupl4fOEzf"; // yes this is ok to publish as it is in the api documentation and just a test account
try {
const response = await fetch(url, {
headers: {
"Content-Type": "text/xml"
}
});
const data = await response.text();
console.log(data);
//return data;
} catch (err) {
console.log(err);
}
}
apiCall();
It seems to be hacked but... working: Using fetch with proxy
var proxy_url = 'https://cors-anywhere.herokuapp.com/';
var main_url = 'https://service.runmyaccounts.com/api/latest/clients/apitest/invoices?api_key=d1bvbxkI8f1bnMBJ4sZiC-xupl4fOEzf';
fetch(proxy_url + main_url)
.then(response => response.text())
.then(data => console.log(data));

Sending email using axios post request to mailgun API [duplicate]

This question already has answers here:
Axios Http client - How to construct Http Post url with form params
(5 answers)
axios post request to send form data
(18 answers)
Closed 3 years ago.
I have been trying to send an email using a post request without luck. I keep getting a 401 (UNAUTHORIZED) error.
Here is my code:
axios.post('https://api.mailgun.net/v3/MY-DOMAIN/messages', {
data: new URLSearchParams({
from: 'from',
to: 'to',
subject: 'subject',
html: 'html'
}),
auth: {
username: 'api',
password: 'MY-API-KEY'
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function (response) {
console.log(response.data)
}).catch(function (error) {
console.log(error.response)
})
I've been sending post requests using axios to other API's fine.
Any ideas?
Thanks.
EDIT:
Here is the mailgun.js method I was using to create messages (which worked) but I couldn't send attachments
var mg = mailgun.client({username: 'api', key: 'MY-API-KEY'})
mg.messages.create('MY-DOMAIN', payload).then(msg => console.log(msg)) // logs response data
.catch(err => console.log(err)) // logs any error
EDIT 2: Mailgun Response
Unfortunately, you would experience issues using Javascript for things like authentication and the Access-Control-Allow-Headers. You might find that authentication (which we require) will not work with the Access-Control-Allow-Headers. We do this intentionally to forbid sending messages from front-end applications because in many cases users would hard-code their API keys and thereby expose their authentication information publicly to the Internet.

JS Fetch - cannot get data from BadRequest response [duplicate]

This question already has answers here:
fetch: Reject promise with JSON error object
(5 answers)
Closed 3 years ago.
I am using React + Redux on the client side and I have the backend in NET CORE.
Client gets data from API using:
return fetch(`api/login`, requestOptions)
.then(response => {
if(!response.ok) {
return Promise.reject(response.json() as Promise<AuthError>);
} else {
return response.json() as Promise<ILoginResponse>
}
})
requstOptions are:
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
};
When the password is wrong, the server returns
404 Bad request
and the body is:
{"errorCode":2,"description":"Invalid Password"}
I would like to read the body but with this code, it is not possible because this response.json() as Promise<AuthError> produces an empty object.
Is there a way how to read the body of a bad request response?
As per the Fetch Documentation:
"The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing."
What you can also check is the Response object documentation. In there, you can check if the Response ok is set to false (so, in a then clause check the response.ok) and from that point on you can check the Response.text property. Check also the Response Documentation
Have you tried using catch and then inspecting error object?
...
.then(response => response.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.dir(error));

Categories

Resources