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
Related
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
I am connecting my ReactJS web app to my .NET Api and I am receiving an error whenever REACTJS is receiving the response from the API.
Here is what the error is saying
The api is returning a STRING which is the JWT token. Here is the code for that particular task:
public IActionResult Login([FromBody] UserLogin userLogin)
{
var user = Authenticate(userLogin);
if (user != null)
{
var token = Generate(user);
return Ok(token);
}
else
{
return NotFound("User not found");
}
}
and here is the fetch method in REACTJS that is responsible for this task:
function getJWTToken(event) {
event.preventDefault();
const userCredentials = {
email: user_email,
password: user_password,
};
const url = Constants.API_URL_LOGIN;
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userCredentials),
})
.then((response) => response.json())
.then((data) => {
console.log("Success:", data);
})
.catch((error) => {
console.error("Error:", error);
});
}
I spent two hours already but I cannot figure out what to do in here since this is my first project using react and .net. Thank you for your help.
Since you are not receiving json but plain text, use response.text() to read the response
I solved my propblem now. Thank you to Stutje, he gave me the idea. Instead of using response.json() , response.text() worked.
i want to get post request response from axios if I have token code I'm able to do that in postman but not able to complete it in axios
here is the postman response and all the require data I have to pass in postman
what I did to get the response in react
React.useEffect(() => {
if (code) {
let configData = {
client_id: 'hjhdjd',
client_secret: 'e637833ndd',
grant_type: 'authorization_code',
redirect_uri: 'http://localhost:3000/linkedin/callback',
code: code,
};
console.log(configData);
axios(
configData
)
.then((response) => {
console.log(response.data.results.bindings);
})
.catch(function (error) {
console.log(error);
});
}
}, [code]);
but after doing this I'm getting error given below
TypeError: Cannot read properties of undefined (reading 'protocol')
You must call methods of axios, in this case you should use post:
axios.post(url,configData).then((response) => {
console.log(response.data.results.bindings);
})
.catch(function (error) {
console.log(error);
});
I made a flask backend and deploy to heroku. It is working when i made a get request and made a post with postman json data. But i cant post when i use axios or fetch in react-native app.
const url = 'https://test.herokuapp.com/list/add';
const config = {
headers: { 'content-type': 'application/json' },
data: {
"test":this.state.testdata
},
};
const response = await axios.post(url, config)
.then(function(res){
console.log(res)
})
.catch(function(error) {
console.log('What happened? ' + error);
}); ```
I have a deleteUser API that deletes a user from my MySql Database.
my API is working perfectly on postman. nut when i call my api from my react app it returns an error
Failed to load resource: the server responded with a status of 401 (Unauthorized)
---this is my delete request---
const handleRowDelete = (oldData, resolve) => {
axios
.post("/deleteUser/" + oldData.userId, {
headers: {
Authorization: "Bearer " + sessionStorage.getItem("token"),
},
})
.then((res) => {
window.location.reload(false);
})
.catch((error) => {
setErrorMessages(["Update failed! Server error"]);
setIserror(true);
resolve();
});
};
and even more i have un updateUser API that im also calling in the same component and it working perfectly
---this is the update api---
axios
.post("/updateUser/" + newData.userId, newData, {
headers: {
Authorization: "Bearer " + sessionStorage.getItem("token"),
},
})
.then((res) => {
window.location.reload(false);
})
.catch((error) => {
setErrorMessages(["Update failed! Server error"]);
setIserror(true);
resolve();
});
} else {
setErrorMessages(errorList);
setIserror(true);
resolve();
}
its exactly the same but the delete api is not working i cant figure out why.(401 unauthorized)
You pass your headers as the second argument to axios.post, but actually it should be third argument. Second argument is data.
axios.post(
"/deleteUser/" + oldData.userId,
{}, // add empty object or null here as second argument
{
headers: {
Authorization: "Bearer " + sessionStorage.getItem("token"),
},
})
Also, if you can modify your API then it would be better to use DELETE method for user deletion, not POST. (and then your code would work because axios.delete accepts headers as second argument)