reactjs fetch get failed but not when using axios? - reactjs

I was using axios in my react app to get/send data from the rest server, but I'm trying to decrease the number of packages I'm importing so I wanted to try using regular fetch method. when I try to get all data using fetch my code works fine, but when I try to get data with specific Id it suddenly fails. but when I switch to axios using the same url, it works fine and I can also see the data using Postman.
this is my code:
const myurl = `${global.config.base_url}/users/${id}`; // http://localhost:8080/users/2
// const response = await fetch(myurl);
// const data = response.json();
// console.log(data); // returns < Pending > in developer tools
const response = await axios.get(myurl);
setUsername(response.data.username);
setEmail(response.data.email);
is there something wrong with my fetch method?

Related

Failed to load resource: the server responded with a status of 500 () in when deployed to vercel next js

i am using next js and i added getServerSideProps to my project and when i redeployed my project to vercel i am getting the flowing error but my localhost is woeking perfectly
i am using next js and i added getServerSideProps to my project and when i redeployed my project to vercel i am getting the flowing error but my localhost is woeking perfectly
export async function getServerSideProps() {
// Fetch data from external API
const res = await fetch(`https://ask-over.herokuapp.com/questapi`);
const data = await res.json();
// console.log(data);
// Pass data to the page via props
return { props: { data } };
}
module.exports = {
reactStrictMode: true,
}
This is the result of an async call not completing before the next line of code that uses that variable runs. This can happen randomly because that is the nature of async code. The fix is to replace the line where you have data.map(...) with data ? data.map(...) : []; which will return an epty array until data gets its value, then the map function will run and your app should be ok.
In javascript, pretty much any time you're using a variable that is the result of an awaited activity, you should have null checks in place. The code above checks if data has value, then if it does have value, it will run return data.map, otherwise it will return [].

react native returning network error when made get request to my django server [ which is running live on server and not on localhost ]

I tried other public api's and they worked but when I try my own GET api created in django rest framework it returns network error.
Note : I have my server running on digital ocean to which I am making request using axios.get() and not to local server.
also I have added in settings.py
CORS_ALLOW_ALL_ORIGINS = True
and when I run the same api's in postman or directly on browser they successfully returns the data, so the problem is with react native code can someone help in guiding where I am wrong.
below the example of my code.
const getData = async () => {
try {
const {data} = await axios.get('https://myGETurl/');
console.log(data);
} catch (error) {
console.log(error.message)
}
};

What's the best way to store a HTTP response in Ionic React?

I'm developing an app with Ionic React, which performs some HTTP requests to an API. The problem is I need to store the response of the request in a local storage so that it is accessible everywhere. The way I'm currently doing it uses #ionic/storage:
let body = {
username: username,
password: password
};
sendRequest('POST', '/login', "userValid", body);
let response = await get("userValid");
if (response.success) {
window.location.href = "/main_tabs";
} else if (!response.success) {
alert("Incorrect password");
}
import { set } from './storage';
// Handles all API requests
export function sendRequest(type: 'GET' | 'POST', route: string, storageKey: string, body?: any) {
let request = new XMLHttpRequest();
let payload = JSON.stringify(body);
let url = `http://localhost:8001${route}`;
request.open(type, url);
request.send(payload);
request.onreadystatechange = () => {
if (request.readyState === 4 && storageKey) {
set(storageKey, request.response);
}
}
}
The problem is that when I get the userValid key the response hasn't come back yet, so even awaiting will return undefined. Because of this I have to send another identical request each time in order for Ionic to read the correct value, which is actually the response from the first request. Is there a correct way of doing this other than just setting timeouts everytime I perform a request?
You are checking for the results of storage before it was set. This is because your sendRequest method is calling an asynchronous XMLHttpRequest request, and you are checking storage before the sendRequest method is complete. This can be fixed by making sendRequest async and restructuring your code a bit.
I would suggest you instead look for examples of ionic react using hooks or an API library - like fetch or Axios. This will make your life much easier, and you should find lots of examples and documentation. Check out some references below to get started:
Example from the Ionic Blog using Hooks
Example using Fetch using React
Related Stack Overflow leveraging Axios

How do I forward a cookie using fetch in getServerSideProps?

I'm using Nextjs for my app. On a page, I would like to fetch data from an authenticated API endpoint ('/api/profile').
I have tried the following, with no success:
export async function getServerSideProps(ctx) {
const { req, res } = ctx
const cookies = cookie.parse(req.headers.cookie ?? '')
const mycookie = cookies[MY_COOKIE] // mycookie exists and is set correctly
if (mycookie) {
const response = await fetch(process.env.SERVER_HOST+'/api/profile', {
credentials: 'same-origin' // I tried with and without this, also tried "include" instead
})
...
I have 2 questions:
Is there a way to avoid having to enter the absolute URL? (I was hoping to simply use '/api/profile', since it's an "internal" api)
How do I make sure the cookie required to fetch data from /api/profile is forwarded through fetch?
N.B: My cookie is httpOnly.
Turns out I'm allowed to manually forward the cookie through:
if (mycookie) {
const response = await fetch(process.env.SERVER_HOST+'/api/profile', {
headers: {
cookie: mycookie
}
})
...
if you use get server side props then the recommended way is to process whatever data fetching functions you have directly in getserversideprops.
calling fetch /api is redundant. what you can do is to extract the function from the api and use it directly in getserversideprops.
what you are doing now is
client -> serverside rendering -> api -> serverside rendering -> client
it can become
client -> serverside rendering -client

Nextjs + expressjs + Azure Web App : two factor authentication with express ('fs' can't be used on client side)

Stack : next.js/express.js/typescript/nodemon
I have a dependency on azure devops api which seems to be using 'fs' under the hood. So I can't use this library in any of the pages (including in getInitialProps).
I created a custom route (call it "get_data") in express server which provides me with the data. I call this route in getInitialProps of the page that will render the data (call it data.tsx) .
The whole app is behind two factor authentication in azure web apps. when get_data call is made in getInitialProps, I get a 401. Note that the origin is the same for serving the page and the get_data api.
Is there a way to pass current auth context when I make the get_data api call ?
In the express api, the method currently looks like this :
server.get('/get_data', (_req, res) => {
let ado = new azure_devops() // this uses the azure-devop-api package
ado.get_data().then((data) => {
res.setHeader('Content-Type', 'application/json');
res.json(data) // return data as json
})
});
Is there a way to merge the two (page and data serving) like the following (so I don't have to make extra api call with auth setup) ?
server.get('/data', (req, res) => { //note the change in route that serves the page data.tsx
const actualPage = '/data';
let ado = new azure_devops() // this uses the azure-devop-api package
ado.get_data().then((data) => {
res.setHeader('Content-Type', 'application/json');
res.write(data) // BUT this is where method returns instead i want to just add to the response body
app.render(req, res, actualPage); // THIS is not executed (so the page doesn't get rendered)
})
});
Appreciate any pointers.
Got the answer from this question.
Still making the API request from getInitialProps. I was missing adding cookie from the context.
const res = await fetch('http://' + context.req.headers.host + '/get_data', {
headers: {
cookie: context.req.headers.cookie, // WAS MISSING THIS
}
});

Resources