Getting response data : 1 when calling an rest-api - reactjs

I'm using react js as the client side and laravel for the api. This happen when i want to get user information within the api however when it hits the api, the data return 1. but when i'm using postman it returns the data normally
Here's the response
react js code:
useEffect(() => {
getUser();
if (loading) {
setLoading(false);
}
}, [loading]);
async function getUser() {
try {
axios.defaults.headers.common["Authorization"] = "Bearer" + token;
const response = await axios({
method: "GET",
url: "api/user",
headers: {
"Access-Control-Allow-Origin": "*",
},
});
console.log(response);
setUser(response);
} catch (error) {
console.log(error);
}
}
laravel api routes :
Route::prefix('v1')->group(function () {
Route::post('login', [UserAuthenticationController::class, 'login']);
Route::post('register', [UserAuthenticationController::class, 'register']);
Route::apiResource('posts', PostController::class)->only(['index', 'show']);
});
Route::prefix('v1')->middleware('auth:sanctum')->group(function () {
Route::post('logout', [UserAuthenticationController::class, 'logout']);
Route::put('profile', [ProfileController::class, 'update']);
Route::apiResource('posts', PostController::class)->only(['update', 'store', 'destroy']);
});
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
i thought it was cors problem in the first place but i've tried solution for cors from the internet and nothing changes.your text

Related

react - getting unauthorized from rest api

I am working on a project where I have used Laravel 9 for the backend and React for the frontend. Whenever i try to make a request it return unauthorized from the backed. But when i try this on the postman it return success response.
I am sure the problem is in my react js code.
const Submited = (e) => {
e.preventDefault();
axios
.post("http://127.0.0.1:8000/api/admin/customer/store", {
headers: {
Authorization: "Bearer" + cookies.jwt,
},
})
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error)
});
};
Put an space character after Bearer

Axios Interceptor is not working in React JS

I am using the below code as an interceptor in my React JS app for getting token back but unfortunately, it is not working. Refresh token returns new idToken and updates local storage data correctly. The same code I'm using some other application which works fine. One main difference is that I currently use React 18 and the previous 16. I struggled to identify the problem but failed. Your help will be appreciable.
axios.interceptors.response.use(
(response) => {
return response;
},
(error) => {
if (error.response.status === 401) {
// console.log(error.response.data.code)
let usersData = JSON.parse(localStorage.getItem("userData"));
const refreshToken = usersData.refreshToken;
return axios
.post(
`${api_base_url}/auth/authentication/refresh_token`,
JSON.stringify({
refresh_token: refreshToken,
})
)
.then((response) => {
usersData["accessToken"] = response.data.data.accessToken;
usersData["idToken"] = response.data.data.idToken;
setSessionStorage("userData", usersData);
error.response.config.headers[
"Authorization"
] = `Bearer ${response.data.data.idToken}`;
return axios(error.response.config);
})
.catch((error) => {
if (error.response.data.code !== "TOKEN_EXPIRED") {
return;
}
localStorage.clear();
window.location = "/login";
});
}
return Promise.reject(error);
}
);
function getIRequestProp(severType, isMultipart, isSocial) {
const serverUrl = severType ? social_api_base_url : api_base_url;
let userData = JSON.parse(localStorage.getItem('userData'));
let idToken;
idToken = userData !== null ? userData['idToken'] : '';
let content_type;
if (isSocial) {
content_type = 'application/x-www-form-urlencoded'
} else {
content_type = isMultipart ? 'multipart/form-data' : 'application/json'
}
return {
serverUrl: serverUrl,
requestHeader: {
'Content-Type': content_type,
'Accept-Language': DEFAULT_LANGUAGE,
Authorization: `Bearer ${idToken}`
}
};
}
async function post(url, body, isSocialServer, isMultipart) {
const {serverUrl, requestHeader} = getIRequestProp(isSocialServer, isMultipart);
return axios.post(serverUrl + url, body, {
headers: requestHeader
});
}
So, I call API like this:
AxiosServices.post(ApiUrlServices.SOCIALS_UPDATE_LINKS(UserInfo.userId), payload, false)
.then(response => {})
What i figured out that return axios(error.response.config); is not sending authorization token in API request headers and trying request infinitely. But consoling error.response.config shows token sets in the config correctly.
Adding an additional modification of axios request, I solved my problem.
axios.interceptors.request.use(request => {
// Edit request config
let usersData = JSON.parse(localStorage.getItem('userData'));
request.headers['Authorization'] = `${usersData.idToken}`;
return request;
}, error => {
return Promise.reject(error);
});

Axios: Pass data in GET method

I have created a config file to create an Axios.
export const http = axios.create({
baseURL: process.env.REACT_APP_API_URI,
responseType: "json",
timeout: 30000,
timeoutErrorMessage: "Request Time out",
headers: {
withCredentials:true
}
})
In the other file, I have created helper functions to post, update, and get. Now I am trying to pass data from the body through the get function so far I have following code to get data without passing the body.
export const getRequest = (url, is_strict = false) => {
return new Promise((resolve, reject) => {
http.get(url, {
headers: getHeaders(is_strict)
}).then((response) => {
if(response.status === StatusCodes.OK || response.status === StatusCodes.CREATED){
resolve(response.data);
} else {
reject(response);
}
})
.catch((error) => {
reject(error);
})
})
}
How can I achieve that?
You cannot have a request body in GET method. You can use request params instead. Or you can use POST method.
Form the MDN docs for GET,
property
avaiability
Request has body
No
Request has body
Yes

Getting status code 304 on a get request with axios using react and redux

I have a get request in my Redux Async Thunk. After calling get to my node.js express server it sends a 304 status code, for some reason I can't get my data.
const userTokenAxios = axios.create({
baseURL: '/api/shoes',
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
});
userTokenAxios.interceptors.response.use((response) => {
if (response.data.errorMessage === 'jwt expired') {
localStorage.removeItem('token');
localStorage.removeItem('user');
}
});
export const getShoesAsync = createAsyncThunk(
'shoes/getShoesAsync',
async (payload, { rejectWithValue }) => {
try {
const response = await userTokenAxios.get('/');
console.log(response);
return response.data;
} catch (error) {
return rejectWithValue(error.response.data);
}
}
);
Its being called from my homepage:
useEffect(() => {
dispatch(getShoesAsync());
}, [dispatch]);
But I can't get any data as every time the page loads the server sends a 304
my backend controller:
exports.getAllShoes = async (req, res, next) => {
try {
let query = Shoe.find({});
const shoes = await query.populate([
{
path: 'user',
select: 'username',
},
]);
return res.status(200).json(shoes);
} catch (err) {
return next(err);
}
};
app.js in my backend folder:
// ROUTES
app.use('/auth', authRouter);
app.use(
'/api',
expressJwt({ secret: process.env.JWT_SECRET, algorithms: ['HS256'] })
);
app.use('/api/shoes', shoeRouter);
package.json in my client folder
"proxy": "http://localhost:9000"
My network preview:
The problem is your interceptor. Response interceptors must return a value, a rejected promise or throw an error, otherwise the resulting promise will resolve with undefined.
It also seems odd that you're intercepting token errors in the successful response interceptor. I would have assumed you'd use the error interceptor.
userTokenAxios.interceptors.response.use(
res => res, // success response interceptor
err => {
// usually you'd look for a 401 status ¯\_(ツ)_/¯
if (err.response?.data?.errorMessage === "jwt expired") {
localStorage.removeItem('token');
localStorage.removeItem('user');
}
return Promise.reject(err);
}
);
If you are actually responding with a 200 status for token errors, you'd need to handle it in the success interceptor
userTokenAxios.interceptors.response.use(
res => {
if (res.data.errorMessage === "jwt expired") {
localStorage.removeItem('token');
localStorage.removeItem('user');
// Make this look like an Axios error
return Promise.reject({
message: "jwt expired",
response: res,
});
}
return res;
}
);
It also looks like you don't need the trailing forward-slash in your request so simply use
const response = await userTokenAxios.get("");

Unable to fetch Data in Netlify Dev Proxy (React)

I've been having CORS error when deploying my app so I decided to try out Netlify Dev.
I followed all steps of the written tutorials but I keep getting errors without being able to identify whats wrong. I haven't even deployed it yet and right now I am having the 403 error, before this was the 500 internal server error.
Please let me know if you notice any obvious mistake on my part.
Here's the node-fetch code:
const fetch = require("node-fetch");
exports.handler = async function () {
const headers = {
"x-api-key": process.env.REACT_APP_MY_API_KEY,
"content-type": "application/json",
};
try {
const response = await fetch("https://api.crimeometer.com", { headers });
if (!response.ok) {
return { statusCode: response.status, body: response.statusText };
}
const data = await response.json();
return {
statusCode: 200,
body: JSON.stringify(data),
};
} catch (err) {
console.log(err);
return {
statusCode: 500,
body: JSON.stringify({ msg: err.message }),
};
}
};
Here's the frontend of my app (with the relevant code):
const initializeApp = useCallback(() => {
async function fetchData() {
try {
let req = new Request(
`./.netlify/functions/node-fetch?lat=${lat}&lon=${lon}&distance=10km&datetime_ini=${newdateyear}&datetime_end=${newdatenow}&page=1`);
const res = await fetch(req);
const info = await res.json();
setCrimes(info.incidents);
} catch (err) {
console.log(err);
}
}
}, [submit, lat, lon]);
useEffect(() => {
initializeApp();
}, [initializeApp]);
This is the error in my console:
This is where i am trying to fetch data from:
https://api.crimeometer.com/v1/incidents/raw-data?lat=${lat}&lon=${lon}&distance=10km&datetime_ini=${newdateyear}&datetime_end=${newdatenow}&page=1
It requires two headers to be set on frontend, which I have done in the netlify function
The API key is currently being added to the React side, where it sets a header and makes a call to the netlify function. But the API key is actually required at the netlify function to request the third party API.
So you have to move the request header from React to Netlify function with something like:
const headers = {
'x-api-key': API_KEY,
'content-type': 'application/json',
}
const response = await fetch(
"https://api.crimeometer.com/v1/incidents/raw-data",
{ headers }
);

Resources