Fetch GET request hitting .catch() on anything but 200 response - reactjs

I have a redux store set up with actions to handle loading accounts. The action calls a service like so:
const requestOptions = {
method: 'GET',
headers: authHeader()
};
return fetch(`http://localapi.co.uk/api/account/load/${account_id}`, requestOptions)
.then(handleResponse)
.then(account => {
if(account.account.id) {
localStorage.setItem('account', JSON.stringify(account))
}
return account;
})
.catch(redirectToLogin)
Handle response is simply a function that checks the .status and .ok properties of the response and either displays an error or logs out if the response status is 401. This works perfectly fine for POST requests. When I hit my login route, any response hits the first .then(handleResponse) and deals with it.
When I send a GET request instead like above 404s, 401s, 500s.. etc all skip the .then(handleResponse) and instead jump to my catch. The problem that causes is that because catch doesn't actually give me a response object to work with I can't check the status - I want to do different things depending on whether the get was a 401 (I want to logout) or a 500 (I want to display a user error stating what went wrong) for example.
Is there a solution that will allow me to get a response or stop my GET requests hitting the .catch and instead hit the response handler I've written?
I'm using:
a Laravel 5.7.20 back-end
a React 16.7.0 front-end
running local node server with npm start

How about having a clean async/await function. Waiting till you JSON data becomes ready and then having the rest of your if logic or returning the account object from the function and moving the rest of the logic to the caller function. Something like this:
async myFunc({ account_id}) {
const url = `http://localapi.co.uk/api/account/load/${account_id}`;
const response = await fetch(url, { headers: headers: authHeader() });
const account = await response.json();
// return account (recommended);
// Place your if logic here (not recommended because its not clean)
}

Related

Django server unable to get data from react Axios

I'm not getting an error but when I saw the logs of my server it prints an empty object {} whenever I send a request to the sever from my react app using axios. I double checked everything every other request in another components of my app works fine, but only in this particular request the data is not being sent! I have no CORS issue!
My react axios request
// PrivateAxios instance to send api request
const axiosPrivate = useAxiosPrivate();
const handleSearch = async () => {
const data = JSON.stringify({ from_company: keyWord });
try {
const response = await axiosPrivate.get(SEARCH_URL, data);
console.log(response);
setRecords(response?.data);
} catch (err) {
if (!err?.response) {
console.log("NO SERVER RESPONSE");
} else {
console.log("SOMETHING WRONG");
}
}
};
Server log
{} <-- Prints the request.data as an empty object
"GET /api/find_many/ HTTP/1.1" 200 6276
The django server responses with correct details when I send a request with Postman or Thunder Client. The server also prints the object that were sent with the Postman request. I don't know why the server is unable to get the object or data when I request from my react app.
Request sent from Postman returns
{'from_company': 'Jethmal Paliwal'} <-- Prints the request.data correctly
"GET /api/find_many/ HTTP/1.1" 200 2284
I have double checked everything, my headers are set correctly, Content-Type: application/json, withCredentials: true, and every other possible settings, Even every request from other components works great, but why this particular request doesn't reach the server?
Tried writing the data as an Object in the request funcion itself
const response = axiosPrivate.get(SEARCH_URL, { "from_company": "Jethmal Paliwal" }); which doesn't work as well. The same empty object gets printed.
Tried JSON.stringify the data, which doesn't work as well.
I believe that axios is omitting the data as it's not per REST standard to submit data in the GET request. HTTP allows that, but people and apparently libraries are not expecting it.
This is the API for axios get method:
axios.get(url[, config])
as you see there is no data in the method signature. And if we look at the POST method:
axios.post(url[, data[, config]])
I suggest if you have data to submit to server that you use a POST method instead.

How to do a HTTP head request in next.js

I want to achieve the same done here but in next.js.
Next.js provides methods to fetch data from a server and using them as props. I don't know whether you want to use it before rendering a page (like getServerSideProps) or when, for example, you click a button, but I suppose its the first case.
My personal preference when doing requests, is axios, so I will use it in this example:
export async function getServerSideProps({ req, res }) {
// Here is where we make the request
const result = await axios({
method: 'HEAD', // here is where we declare that we want to use the HEAD method
url: "your server url", // this is the url where we want to send the request
headers: {} // if you want to add custom headers, you can do it here
})
// Here we are logging the result of the request
console.log(result)
}
You can refer to the next.js documentation on data fetching and the axios documentation
Have a great day and I hope you succeed on your projects

Post Request from axios always returns Unauthorized despite having valid JWT set in header/Axios Deletes Headers

I set up passport-local to login a user, and then once logged in, the user will be given a JWT token through passport-JWT. The JWTStrategy is set up to use
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken() so that the JWT can sent with the Authorization header Authorization: `Token ${userContext.token}`}. In my react client side, I have set up a GET request using axios as shown here:
const fetchProfileDetails = async(config)=>{
const res = await axios.get("http://localhost:8080/users/me", config)
}
const config = {
method:"GET",
withCredentials: true,
headers: {Authorization: `Bearer ${userContext.token}`}
}
This request successfully authenticates and returns the user data from /me.
Now heres the kicker: when I use the exact same request structure, but switch the method to post in the axios request and in my express route in the backend, the request always responds with a 401 Unauthorized.
However, when I send the same request from POSTMAN, with the same Bearer Token used in the request that was Unauthorized, the request succeeds without any errors.
TLDR: GET requests work with the JWT token and return with a 200 status code, while the same request with a POST method returns with a 401 status code.
What am I missing here??!
You are probably using there GET and not using POST anywhere.
In your code, you have code only for get. You will need to write code for post as well.
Below is the code for post for your reference:
router.post('/', config, async(req, res, next) => {
const { error } = validateBody(req.body);
if (error) {
return res.status(400).send(error.details[0].message);
}
const newData= new passport({ name: req.body.name });
await newData.save();
console.log('saving the document');
res.send(newData);
})
Your code should have post as well. Writing single code will not work. You need to have to write code for every condition and every possibility. So like for get need code for post as well, also if you have condition for patch or delete or put you will have to write the axios method for that as well.
Hope this has helped you in any way.
I have come upon a solution for this issue. For some reason, axios was not maintaining the Authorization header I had set in my config variable, and deleted it upon making the request. To solve this, I just had to reshuffle my axios request to look like this:
const res = await axios({
method:'POST',
url:"http://localhost:8080/users/test",
headers:{'Authorization':`Bearer${token}`
}})
I feel cheated as I spent a ton of time on this and the solution was so underwhelming. Axios was trolling me the whole time :/

Get cookie/localStorage value in nextjs API request

I'm trying to get cookie or localStorage value in my API request. When I'm trying to access localStorage I get error that localStorage is not defined, cookies are undefined, I tried my luck with AsyncLocalStorage, but I'm getting error that window is undefined. There is any way to get saved value in this asynchronous function?
import AsyncLocalStorage from '#createnextapp/async-local-storage'
export default async (req, res) => {
try {
let data = await AsyncLocalStorage.getItem('#key')
console.log(data)
}catch(error){
console.log(error)
}
}
This is expected. When you process the data in your API it is actually running in the server. Localstorage, and cookies however are browser based storage (This is also why window is undefined, servers don't have windows). As a result they are not available to the API to leverage. Instead when you make the API request you need to add the data into a header which can then be parsed on your server.
Setting a header on your request:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader
From there you should be able to read the headers through:
(req, res) => {
// look at all these great headers we have
const { headers } = req;
}

React, Fetch-API, no-cors, opaque response, but still in browser memory

I've been trying to make an React site, which would fetch a GET-response from API and print it out to my .html-file. I've managed to fetch the file just right, but i can't access the JSON-data server sends me.
If i use no-cors in my Fetch-request, i get an opaque response containing pretty much nothing, but if i go to Developer tools i can find my data there and read it. If i do use cors, almost same thing. I get an 403-error, but my data is in the browser memory, but my code doesn't print it out. I can find the response from Network in developer tools.
Why does the server give me an error, but still i get my data? And how can i access it, if it's in the browser?
class Clock extends React.Component {
constructor(props) {
super(props)
this.state = {data2: []}
this.apihaku = this.apihaku.bind(this)
}
componentDidMount() {
this.apihaku(),
console.log("Hei")
}
apihaku () {
fetch('https://#######/mapi/profile/',
{method: 'GET', mode:'no-cors', credentials: 'include',
headers: {Accept: 'application/json'}}
).then((response) => {
console.log(response);
response.json().then((data) =>{
console.log(data);
});
});
}
render() {
return <div>
<button>Button</button>
</div>
}}
ReactDOM.render(
<Clock />,
document.getElementById('content')
)
EDIT: Error images after trying out suggestions
https://i.stack.imgur.com/wp693.png
https://i.stack.imgur.com/07rSG.png
https://i.stack.imgur.com/XwZsR.png
You're getting an opaque response, because you're using fetch with mode: 'no-cors'. You need to use mode: 'cors' and the server needs to send the required CORS headers in order to access the response.
Fetch is doing exactly what the documentation says it's supposed to do, from Mozilla:
The fetch specification differs from jQuery.ajax() in two main ways:
The Promise returned from fetch() won’t reject on HTTP error status
even if the response is an HTTP 404 or 500. Instead, it will resolve
normally (with ok status set to false), and it will only reject on
network failure or if anything prevented the request from completing.
By default, fetch won't send or receive any cookies from the server,
resulting in unauthenticated requests if the site relies on
maintaining a user session (to send cookies, the credentials init
option must be set). Since Aug 25, 2017. The spec changed the default
credentials policy to same-origin. Firefox changed since 61.0b13.
So you need to use CORS, otherwise you get an opaque response (no JSON), and then 403 to me suggests that you haven't authenticated properly. Test your API with Postman, if I had to take a guess I'd say the API isn't sending the cookie because it's a GET request, so no matter how well you set your headers on the client it won't work. Try it as a POST instead. GET requests should really only be used to drop the initial HTML in the browser. I think for your headers use these, include the creds that the API sends and allow the domain to be different.
mode: "cors", // no-cors, cors, *same-origin *=default
credentials: "include", // *same-origin
Try this and see where is the error happening i believe in the parsing but lets check and see
fetch(https://#######/mapi/profile/, {
method: "GET",
headers: {
"Content-Type": "application/json"
},
credentials: "include"
})
.then((response) => {
console.log(response);
try {
JSON.parse(response)
}
catch(err){
console.log("parsing err ",err)
}
})
.catch((err)=>{
console.log("err ",err)
});
I had a similar issue, this kind of problem happend when a HTTP port try to send request to a HTTPS endpoint, adding a "mode:'no-cors'" doesn't do what is SOUND doing but rathere when the documentation says.
I fixed the issue by allowing in my API Application for calls from my HTTP port
(i'm using a .net 6 as an API in debugging mode, my code look like this https://stackoverflow.com/a/31942128/9570006)

Resources