next.js fetch data from Laravel - javascript

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

Related

Sending file and data with Fetch

I have an application in react. The state of my application is as follows
const [book, setBook] = useState({
title: '',
cover: {}
numberPages: 0,
resume: '',
date: date,
});
Cover prop contains a file. When I try to convert the state to json (JSON.stringify(book)) to send it with FETCH, the cover property is an empty object. How can I send this information correctly?
My on submit event form
let handleForm = (e) => {
data = JSON.stringify(book);
let info = {
method: 'POST',
body: data,
headers: {
'X-CSRF-TOKEN': header,
"Content-Type": "application/json",
"Accept": "application/json, text-plain, */*"
}
}
fetch('/books/add', info)
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log(error));
e.preventDefault();
}
when you are sending files in fetch make sure u use the formdata
var data = new FormData()
data.append('title', book.title)
data.append('cover', book.cover)
fetch('/', {
method: 'POST',
body: data
})
Hope it works. If not please comment your code where you are making api call

React fetch('http://localhost:3000/profile/:id')

as the title says, I am trying to fetch this URL from node/express server. The route is working fine in Postman, so I believe it tells me the mistake is in my fetch method.
my code:
onSubmitSave = () => {
fetch('http://localhost:3000/profile/:id', {
method: 'put',
headers: {'Content-Type': 'application/json' },
body: JSON.stringify({
name: this.state.name,
telephone: this.state.telephone,
})
})
.then(response => response.json())
.then(user => {
console.log(user);
}).catch(err => console.log(err))
}
I would be glad if anyone could help me with that.
I don't see your :id being replaced by any string interpolation. You might be looking for something like this:
fetch(`http://localhost:3000/profile/${this.id}`)

Unable to fetch resource with fetch, NetworkError

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?

React Native send Json.Stringify data to Laravel controller get "Unrecognized token '<'"

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

React Redux Fetch action returning "415 (Unsupported Media Type)" and "401 (unauthorized)"

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',
}
})

Categories

Resources