I'm using laravel 5.8 with react and axios. I built a login page and i get a console "bad request" error after login failed. I get the correct response from the server, but i keep getting the a console error of the post request.
Here is the request :
export const getProfile = () => {
return axios
.get('api/profile', {
headers: { Authorization: `Bearer ${localStorage.usertoken}` }
})
.then(response => {
return response.data
})
.catch(err => {
console.log(err)
})
}
And here is the login function from the UserController
public function login(Request $request)
{
$credentials = $request->json()->all();
try {
if (!$token = JWTAuth::attempt($credentials)) {
$loginsCount = 0; //init counter
if ($request->session()->has('userLoginsCount')) {
//get session value
$loginsCount = $request->session()->get('userLoginsCount');
//check login attempts count
if ($loginsCount == 5) {
$current_timestamp = now()->timestamp;
Log::info($current_timestamp.' User exceeded alowed
login attempts : '.$request->ip());
$request->session()->put('userLoginsCount', 0);
return;
} else {
//increment it
$loginsCount++;
// set the new value
$request->session()->put('userLoginsCount',
$loginsCount);
}
} else {
$request->session()->put('userLoginsCount', $loginsCount);
}
//Store session
Session::save();
return response()->json(['error' => 'invalid credentials'],
400);
}
} catch (JWTExecption $e) {
return response()->json(['error' => 'could not create token'], 500);
}
return response()->json(compact('token'));
}
Api Routes:
Route::post('register', 'UserController#register');
Route::post('login', 'UserController#login');
Route::get('profile', 'UserController#getAuthenticatedUser');
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Web Routes:
Auth::routes();
Route::get( '/{path?}', function(){
return view( 'layouts/app' );
} )->where('path', '.*');
Here pictures of the error
I believe these are the steps to fix everything.
1. Change error response to 401 (not authorized).
return response()->json(['error' => 'invalid credentials'], 401);
2. Retrieve the error message from the axios error response before use.
export const getProfile = () => {
return axios
.get('api/profile', {
headers: { Authorization: `Bearer ${localStorage.usertoken}` }
})
.then(response => {
return response.data
})
.catch(err => {
// retrieve the error message
let message = err.response.data.error;
console.log(message);
// now you can do something with 'message'
// ...
})
You were dumping the whole error to the console, not pulling out the actual message. I'm sorry I overlooked this.
Related
err.response.data giving back the data I am looking for !!
Status code 302
The data is captured in the catch block instead of try block
This is the reudx slice code
export const getAllProject = async (dispatch) => {
try {
console.log("before");
const res = await apiLink.get(`/getAllProjects`);
console.log(res.data);
console.log("after");
dispatch(getAllProjectSuccess(res.data));
} catch (error) {
console.log(error.response.data);
// toast.error(error.response?.data.message);
}
};
The API is calling and the data is also coming.
I inspected the network tab
And also working in postman
But after the await, the code is not running.
React router version 5 is used in this project.
this is the proof of API calling
and
using axios interceptor like this
apiLink.interceptors.request.use(
async (config) => {
const TOKEN = JSON.parse(localStorage.getItem("accessToken"));
config.headers["authorization"] = "Bearer " + TOKEN;
return config;
},
(error) => {
return Promise.reject(error);
}
);
apiLink.interceptors.response.use(
function (response) {
return response;
},
function (err) {
if (err.response?.status === 500) {
userLogout();
}
return Promise.reject(err);
}
);
export default apiLink;
Edited:
err.response.data giving back the data I am looking for !!
I just log that and the status code of receiving the data is 302 .
I am using redux approach in react js.I am calling getRolesPagination()
with service getRolesPagination() and pass handleResponse() in service to catch response/error.
It is working fine but when the server respond with 401 status error it doesn't catch the error.
I have to catch it to log out user because if user token get invalidate then the server responds with 401 status and
"{error :Unauthorized}"
function getRolesPagination(page, filter, sort, pageSize){
return dispatch => {
dispatch(request())
roleService.getRolesPagination(page, filter, sort, pageSize)
.then(
response => {
dispatch(success(response));
},
error => {
dispatch(failure(error));
dispatch(alertActions.error(error));
}
);
};
function request() { return { type: adminConstants.PAGINATION_ROLES_REQUEST } }
function success(response) { return { type: adminConstants.PAGINATION_ROLES_SUCCESS, payload:response } }
function failure(error) { return { type: adminConstants.PAGINATION_ROLES_FAILURE, payload:error } }
}
roleService.getRolesPagination function:
function getRolesPagination(page, filter, sort, pageSize){
const requestOptions = {
method : 'GET',
headers : authHeader()
};Why 401 errors is not getting caught with the fetch function in reactJS?
return fetch(baseUrl+'roles?page='+page+'&filter='+filter+'&sort='+sort+'&pageSize='+pageSize, requestOptions).then(handleResponse);
}
handleResponse function:
export function handleResponse(response) {
return response.json().then(data => {
if (!response.ok) {
if (response.status === 401) {
localStorage.removeItem('user');
window.location.reload(true);
}
const error = (data && data.error) || response.statusText;
return Promise.reject(error);
}
return data;
});
}
please check the status of the response, 401 is a valid server response it won't go to catch block
fetch(request)
.then(function(response) {
if (response.status !== 200) {
/*your code */
}else{
throw new Error(response.status)
}
})
.catch(function(error) {
/*logout logic*/
});
l am making a request like that
axios.get(`api/projects/${id}`)
.then((response) => {
console.log(response);
})
.catch((response) => {
console.log(response);
dispatch({
type: ActionTypes.ERROR,
error: response.data
});
});
resposne function on server
export function getProject(req, res) {
const projectId = req.params.project_id;
Project.findById(projectId)
.populate('user', 'username')
.exec((err, project) => {
if (err || !project) {
get404(html => res.send(html));
return ;
}
else {
return res.json(project);
}
});
}
get404 is a function which return the 404 html on server
what l want to do is once get404 triggered, it should return the 404 page,bu now it returns the whole html page to resposne.data. Anyone gives some suggestion?
Thanks in advance!
I am getting above error while fetching some data from the API. Following is the code of the action creator where I am trying GET the data:
import { FETCH_USER } from './types';
import axios from 'axios';
export const fetchUser = () => async dispatch => {
console.log('fetchUser');
const res= await axios.get('/api/current_user');
dispatch({ type: FETCH_USER, payload: res });
};
Also when I am debugging in the code editor, console is giving me below error:
SyntaxError: Unexpected token import
Generally this error comes when the url/location provided inside GET method is not correct.
So check the url/location again and correct it.
So most probably there is some mistake here : '/api/current_user'
In my case it was a minor syntax error (a misplacement of my brackets).
My code looked like this:
axiosget("/api-url").then(
(response) => {
doSomething();
}), () => {
doError();
}
);
instead of this:
axiosget("/api-url").then(
(response) => {
doSomething();
}, () => {
doError();
});
);
If you get this error message it means that your error handling-code isn't there or that it could not be reached, therefore the promise was unhandled (since the catch-part of your wasn't properly setup).
If you get this message always doublecheck your syntax!
If your are using laravel for API and vue/Nuxtjs for frontend and axios for send data to API....
This type of errors can be faced for laravel validation error sending not in correct way using try{} catch(){} block or receiving errors by axios not in correct way to using try() catch(){} block.
Here, try catch block using for error handling.
If your API routes called the public function its name "register()", so your function inside your controller have to like following...(I am using laravel-8 for API)
public function register(Request $request) {
try {
$fields = $request->validate([
'name' => 'required|string',
'email' => 'required|string|email|unique:users',
'password' => 'required|string|confirmed',
]);
$user = User::create([
'name' => $fields['name'],
'email' => $fields['email'],
'password' => bcrypt($fields['password'])
]);
$token = $user->createToken('myapptoken')->plainTextToken;
$response = [
'user' => $user,
'token' => $token,
];
return response()->json($response, 200);
} catch(ValidationException $e) {
return response()->json([
'status' => 'error',
'msg' => 'error',
'errors' => $e->errors()
], 422);
}
}
and Frontend Nuxt or vue methods name is "registerNewUser()" so, codes can be following for error handling...
async registerNewUser() {
try {
let data = {
name : this.name.trim(),
email : this.email.trim(),
password : this.password.trim(),
password_confirmation : this.password_confirmation.trim(),
};
let headers = {
headers: {
'Accept': 'application/json',
}
};
await this.$axios
.post("/api/register", data, headers)
.then((response) => {
console.log("response", response);
if(response) {
// console.log(response)
} else {
}
});
} catch(err) {
// here we are receiving validation errors
console.log("Err == ", err.response);
console.log(err.response.data.errors);
}
}
You are receiving response inside axios then block or receive error inside catch block using err.response
Here,
let data = {
name : this.name.trim(),
email : this.email.trim(),
password : this.password.trim(),
password_confirmation : this.password_confirmation.trim(),
};
Given codes is for data of Nuxtjs or vuejs. If not know that you can using like following data or any other data...
let data = {
name : 'Kallol',
email : 'kallolray94#gmail.com',
password : '123456',
password_confirmation : '123456',
};
First-time Stack Overflow poster here!
I’m following an Angular 4 tutorial, and completing its authentication section with Firebase (link: ). I was able to successfully signup and login, but receive errors when passing the user’ token, via ‘getIdToken’, to my GET request to limit certain actions to authenticated users.
When passing my token to my GET request, I get the following error:
* Response {_body: "{↵ "error" : "Could not parse auth token."↵}↵", status: 401, ok: false, statusText: "Unauthorized", headers: Headers…}
I also experience this issue when copying and pasting tokens from the console into code
I’ve posted the (potentially) most relevant code below for debugging:
header.component.ts
onFetchData() {
this.dataStorageService.getRecipes();
}
data-storage.service.ts
getRecipes() {
const token = this.auth.getTokenGrabber()
this.http.get('https://recipes-fe1ba.firebaseio.com/.json?auth=' + token)
.map(
(response: Response) => {
console.log(response.json())
const recipes: Recipe[] = response.json();
for (let recipe of recipes) {
if (!recipe['ingredients']) {
recipe['ingredients'] = [];
}
}
return recipes;
}
)
.subscribe(
(recipes: Recipe[]) => {
this.recipeService.setRecipes(recipes);
}
);
}
authentication.service.ts
signinUser(email, password){
firebase.auth().signInWithEmailAndPassword(email, password)
.then(
(response) => {
firebase.auth().currentUser.getIdToken(
).then(
(token:string) => {
// console.log(token)
this.token = token
console.log('user was found')
// console.log(this.token)
}
)
}
).catch((erorr) => {
console.log('user was not found')
}
)
}
getTokenGrabber(){
firebase.auth().currentUser.getIdToken()
.then(
(token:string) =>
this.token = token
)
return this.token
}
}
The REST API documentation indicates the query parameter is access_token, not auth. Give this a try:
this.http.get('https://recipes-fe1ba.firebaseio.com/.json?access_token=' + token)