I am trying to post data from react native app by json.stringify to Laravel controller. But getting "JSON Parse error: Unrecognized token '<'". I need help how to resolve it. My code are given below:
js code
fetch(API_URL+'/signup', {
method: 'post',
header:{
'Accept': 'application/json',
'Content-type': 'application/json'
},
body:JSON.stringify({
name: userName,
email: userEmail,
password: userPassword
})
})
.then((response) => response.json())
.then((response) =>{
alert(response);
})
.catch((error)=>{
console.error(error);
});
Laravel:
public function registerUser()
{
$this->validate(request(), [
'email' => 'required|email',
'name' => 'required',
'password' => 'required|min:4|confirmed'
]);
$user = User::create(request(['email', 'name', 'password']));
return "success";
}
Server return is not a json. You can post the return of the requisition?
what the answer above is trying to say is that you are supposed to do
return response()->json("success");
instead of
return "success";
its here
https://laravel.com/docs/5.5/responses#json-responses
Related
currently I'm fetching data from my api to front-end. I checked and my request body is arriving to server side. But after doing things when it comes to returning the token it always returns undefined data to vue.js:
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody]User user)
{
var result = await _accountRepository.LoginAsync(user.username, user.password);
if (string.IsNullOrEmpty(result))
{
return Unauthorized(result);
}
Debug.WriteLine(result.ToString()); // this works and I can see the token
return Ok(result);
}
When it comes here:
methods: {
login() {
fetch("http://localhost:60427/api/account/login", {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
username: this.username,
password: this.password,
})
}).then(response => {
console.log(response.data); // this is always undefined
})
.catch(e => {
console.log(e);
});
},
}
Please help I can't see any errors here. I'm confused.
You need to call either Response.text() or Response.json() depending on what data you expect. These methods return a Promise that resolves to the data.
E.g. for JSON:
fetch("http://localhost:60427/api/account/login", {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
username: this.username,
password: this.password,
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.error(e));
i am writing a simple user register using Laravel with a simple code
public function register()
{
$this->validate(request(), [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required'
]);
$user = User::create(request(['name', 'email', 'password']));
auth()->login($user);
return [
'status' => true,
'user' => $user
];
}
then i am sending the data form Next.Js :
using axios:
let config = {
method: 'post',
url: `http://localhost:8000/api/register`,
headers: {
'Content-Type': 'application/json',
},
data: values,
}
axios(config)
.then(json => console.log(json))
it's work fine, but i send an used email address, it will through 422 code, and axios can't catch the result
using fetch:
fetch('http://localhost:8000/api/register', {
method: "post",
mode: 'no-cors',
body: new URLSearchParams(data)
}).then(res => res.json())
.then(json => console.log(json))
also work but when use used email, it will send 302 code , and call the index /
I think that you have missed adding the .catch(...) to return the error object like the example in docs
Axios docs
This question already has answers here:
Receive JSON POST with PHP
(12 answers)
Closed 4 years ago.
I am using fetch in react native application to send a post request as:
const data = {
name: 'name',
email: 'email'
}
try{
var r = await fetch(SEND_INITIAL_DATA, {
method: 'POST',
body: JSON.stringify(data),
headers:{
'Content-Type': 'application/json'
}
});
}catch(err){
console.log(err);
}
console.log(r);
I am using php in my backend server. but I am unable to access the parameters in php and printing the $_POST is missing body
PHP :
<?php
require 'connect.php';
echo json_decode($_POST); // printing the post
RESPONE
What am I missing ?
It's better to use then and catch in fetch for better debugging. example:
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Change your code to:
const data = {
name: 'name',
email: 'email'
}
await fetch(SEND_INITIAL_DATA, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
return response.json();
})
.then(function(myJson) {
console.warn(myJson);
});
If you have an error, it will be printed and you can debug it.
I'm fetching data from my API using this. It will post email and password to my API
onSubmitSignIn = () => {
fetch('http://localhost:3001/signin', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signInEmail,
password: this.state.signInPassword
})
})
.then(response => response.json())
.then(data => {
if (data === 'login success') {
this.props.onRouteChange('home');
}
})
.catch((e) => console.log(e))
};
and the request will be handled in the API by this
app.post('/signin', (req, res) => {
if (req.body.email === db.users[0].email && req.body.password === db.users[0].password) {
res.json('login success')
} else {
res.json('login fail')
}
});
This will result in TypeError: NetworkError when attempting to fetch resource.
However, if the .then are removed and the this.props.onRouteChange('home'); is added below like this
onSubmitSignIn = () => {
fetch('http://localhost:3001/signin', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signInEmail,
password: this.state.signInPassword
})
})
this.props.onRouteChange('home');
};
it will work and I can log in without errors.
But, the same error will still be shown if this.props.onRouteChange('home'); is removed like this
onSubmitSignIn = () => {
fetch('http://localhost:3001/signin', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signInEmail,
password: this.state.signInPassword
})
})
};
I've also double checked my API with Postman and the post request was successful.
This a odd problem for me and I'm new to javascript, please forgive me if this happens to be a careless newbie mistake. Thanks.
P.S. Please let me know if more code is needed.
Are you running the app on the same client that's hosting it? Try changing localhost to your client's LAN IP and see if that makes a difference?
I have an action that creates a fetch to POST a client back to the API.
I send a JWT in the "headers" which by itself is not the problem as its also used in a GET that works just fine... but not in a POST. Here is my action:
export const createNewClient = (payload) =>
(dispatch, getState) => {
dispatch({ type: REQUEST_CREATE_NEW_CLIENT, payload })
const jwt = getJwt()
if (!jwt) {
throw new Error('No JWT present')
}
const token = jwt.access_token
const headers = new Headers({
'Authorization': `bearer ${token}`
})
debugger
const task = fetch('/api/client/create', {
method: 'POST',
body: JSON.stringify(payload),
headers,
})
.then(handleErrors)
.then(response => response.json())
.then(data => {
dispatch({ type: RECEIVE_CREATE_NEW_CLIENT, payload: data })
dispatch({
type: SAVE_MESSAGE, payload: {
message: "Successfully saved client",
type: 'success'
}
})
})
.catch(error => {
//clearJwt()
dispatch({ type: ERROR_CREATE_NEW_CLIENT, payload: error.message })
dispatch({ type: SAVE_MESSAGE, payload: { message: error.message, type: 'error' } })
})
addTask(task)
return task
}
I tried modifying the headers to include UTF-8 like so.
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
However this just gave me 401 Unauthorized which means that by using this it is the correct media type but now wont be accepted.
That same JWT works fine in a Fetch GET command so the JWT itself is not the problem - I believe it might be the way I am writing the "Fetch".
Now I do the same thing in Postman and I get through but not with this Fetch...
What have I missed or incorrectly structured for a Fetch POST so that JWT is accepted etc
If it works as in the provided image
then the following will work
fetch('/api/client/create', {
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Authorization': `bearer ${token}`,
'Content-Type': 'application/json',
}
})