How to get the response object of an ajax request with laravel? - javascript

Guys I'm making a fetch request for laravel without using jquery and I would like to get the return of this request, however when I give a console.log() in the response the console informs undefined.
This is my request:
fetch(action, {
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-Token": token
},
method: "post",
credentials: "same-origin",
body: JSON.stringify({
email: email,
password: password
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.log(err))
This is my controller that returns the empty field information:
public function login(Request $request)
{
if (in_array('', $request->only('email', 'password'))) {
$json['message'] = "Empty";
return response()->json($json);
}
var_dump($request->all());
}
The request was successful and the browser informs the response message:
Object response message
However console.log(data) returns undefined, how can I return the object that contains the message?
Taking advantage of the question, is this the best way to make this request?
Thank you guys

Related

VM1661:1 Uncaught (in promise) SyntaxError: Unexpected token s in JSON at position 0

Hi guys there have been an error in my site for quite long and I have searched whole internet for the answers but didn't found any solutions here is my onsubmit code
onSubmit = () => {
fetch("http://localhost:2000/signin", {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: this.state.signinEmail,
password: this.state.signinPassword,
}),
})
.then((response) => response.json())
.then(console.log(this.state.signinEmail, this.state.signinPassword))
.then((data) => console.log(data));
};
Also i have checked the response of the network tab it says success but getting this error don't know how to get rid of it. I have also checked the solution of the
Stackoverflow that write Accept:application/json but still didn't worked,but it gives me "bad request" error
The backend code is:
app.post("/signin", (req, res) => {
if (
req.body.email === database.users[0].email &&
req.body.password === database.users[0].password
) {
res.send("success");
} else {
res.status(400).json("error logging in");
}
});
I have also tested it through Postman it works successfully on it with no errors.
This the json server.
This happens when you make a request to the server and parse the response as JSON, but it’s not JSON.
fetch('/url').then(res => res.json())
The actual request worked fine. It got a response. But the res.json() is what failed.
The root cause is that the server returned HTML or some other non-JSON string.
You can try changing res.json() to res.text().
onSubmit = () => {
fetch("http://localhost:2000/signin", {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email: this.state.signinEmail,
password: this.state.signinPassword,
}),
})
.then((response) => response.text())
.then((data) => console.log(data));
};

How to make a HTTP post request like a HTML form using Axios?

I am trying to connect to an API (nova.astrometry.net) that requires an HTTP post request just like a form (x-www-form-encoded). I am using Axios for that, but still, I am getting this error as a response from the API { status: 'error', errormessage: 'no json' }
Here's the code for reference
axios({
method: 'post',
url: 'http://nova.astrometry.net/api/login',
data: {
'request-json': JSON.stringify({ "apikey": process.env.API_KEY })
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
}).then((response) => {
console.log(response.data)
});
I also tried using the request library but got the same response.
The content type required by the api is 'application/x-www-form-urlencoded' but you are sending 'application/json'.
To send that data, do the following:
const body = new URLSearchParams();
body.append('request-json', JSON.stringify({ "apikey": process.env.API_KEY }));
Then use the above body in the body field of axios.
axios.post('http://nova.astrometry.net/api/login', body, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(res => console.log(res.body))
.catch(console.error);

React native 422 Unprocessable Entity error returned from server when using POST Fetch call with content type: application/x-www-form-urlencoded

I'm calling a simple login API with POST request following are the params:
Headers:
Content-type: application/x-www-form-urlencoded
Body:
email: String
password
Error returned from server is:422 Unprocessable Entity
CODE:
var formBody = new FormData();
formBody.set("email", "test5#gmail.com");
formBody.set("password", "12345678");
const data = new URLSearchParams(new FormData(details));
return dispatch => {
dispatch(requestData());
try {
fetch(`${BASE_URL}users/sign_in`, {
method: 'POST',
// headers: Interceptor.getHeaders(),
headers: {
Accept:'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
// body: formBody
body: data
})
.then(res => res.json())
.then(result=>
{
if (result.success === false) {}
}
)
} catch (error) {
console.log('error',error)
dispatch(failureData(error))
}
}
Screenshot of code
Got the answer, 422 is basically caused by semantic issue, in my case, Origin of my Request Header was going null.

Adding a user using fetch with POST method

Using the following code, I'm trying to add a new user and console log all users including the new added one:
const url = "https://jsonplaceholder.typicode.com/users";
// Creating a user
fetch(url, {
method: "POST",
body: JSON.stringify({
name: "Robert Miller",
username: "robby",
email: "roby#outlook.com"
}),
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(response => console.log(response));
However, the console.log shows only the added user but not all users.
My assumption was that because the method of the fetch is POST, I need to send another request via GET to get all users and came up with this:
const url = "https://jsonplaceholder.typicode.com/users";
// Creating a user
fetch(url, {
method: "POST",
body: JSON.stringify({
name: "Robert Miller",
username: "robby",
email: "roby#outlook.com"
}),
headers: {
Accept: "application/json, text/plain, */*",
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(response => console.log(response));
fetchAllUsers();
function fetchAllUsers() {
fetch(url)
.then(response => {
if (!response.ok) {
throw Error(response.statusText);
}
// Read the response as json.
return response.json();
})
.then(data => {
// Do stuff with the JSON
console.log(data);
})
.catch(error => {
console.log("Looks like there was a problem: \n", error);
});
}
But I still cannot see the added user in the list. Any help?
I think this link is answer your question:
Unable to post a new user
Since JSONPlaceholder is a shared API used by many, modifications are faked (POST, PUT, PATCH) and resources are read-only. This is to avoid user "A" creating new resources and having user "B" impacted by them.
If you need to make changes and persist them between calls, you can run JSON Server locally.

How to store asynchronous data inside a variable Fetch API

I am working on a project that uses Laravel for back-end and React for front-end.
Whenever the user clicks login, a modal will open that will, up on submitting, fetch the users bearer token.
These fetch functions are all located inside AuthService.js
export function getLoginToken(email, password) {
fetch("/api/login", {
method: "post",
credentials: 'include',
headers: {
'Accept': 'application/json',
"Content-type": "application/json",
},
body: JSON.stringify({
'email': email,
'password': password
})
}).then((response) => response.json())
.then((responseJSON) => {
return responseJSON;
})
}
The Nav component is where the login button resides, so I'm importing and using the funcionts that I've created inside AuthService.js
When I console log the json result within the actual getLoginToken function, there is no problem. Because up on placing it inside .then() it waits for it to complete so it doesn't result in undefined.
Now.. Inside the Nav component, there is an onClick function bound to the login button, which will execute AuthService.getLoginToken(email, password)
Actual problem:
I would like to store the response data inside a variable, but i keep getting undefined. This because I'm trying to insert asynchronous data inside a synchronous function.
I've also tried:
AuthService.getLoginToken(loginEmail, loginPassword).then((result) => {
this.setState({
token: result
});
});
But this will also return: Cannot read property 'then' of undefined.
Any ideas on how to fix this?
Try this
export function getLoginToken(email, password) {
return fetch("/api/login", {
method: "post",
credentials: 'include',
headers: {
'Accept': 'application/json',
"Content-type": "application/json",
},
body: JSON.stringify({
'email': email,
'password': password
})
}).then((response) => response.json())
.then((responseJSON) => {
return responseJSON;
})
}
Proper way would be to use state management tool like redux
You can use async await. Or use redux-thunk if you are doing redux.

Categories