React Native axios api call Shopify - reactjs

Good morning guys, I try to fetch data from Shopify using this method. But it does not working.
Request failed with status code 400
May you share your little experience ?
I'm working on React Native Project.
const api_key = "example-api-key";
const password = "example-password";
const version = "2021-07";
const url = `https://${api_key}:${password}#store-example.myshopify.com/admin/api/${version}/products.json`;
useEffect(() => {
axios({
method:'get',
url:url
}).then((result) => {
console.log(result.data)
}).catch(error => {
console.log(error)
})
});

It's most likely that the authentication is failing. Move the auth parameters to axios header. Try this
const username = "example-api-key";
const password = "example-password";
const version = "2021-07";
const url = `https://store-example.myshopify.com/admin/api/${version}/products.json`;
useEffect(() => {
axios({
method:'get',
url,
auth: { username,password }
}).then((result) => {
console.log(result.data)
}).catch(error => {
console.log(error)
})
});

Related

Post form-data on Axios (React)

I've got the following component in React:
const login = async (username, password) => {
const response = await axios.post('/auth/jwt/login', {
username,
password
});
const {accessToken, user} = response.data;
setSession(accessToken);
dispatch({
type: 'LOGIN',
payload: {
user,
},
});
};
Now, the problem is my API is expecting a form, whereas this request is sending a json on the body, thus I'm getting a 422 error (unprocessable entity).
I've tried creating a FormData() object but no luck so far:
const formData = new FormData();
const login = async () => {
const response = await axios.post('/auth/jwt/login', {
username: formData.username,
password: formData.password
});
const {accessToken, user} = response.data;
setSession(accessToken);
dispatch({
type: 'LOGIN',
payload: {
user,
},
});
};
Can anyone please help me? Thanks!
Specifically you want to POST the data as application/x-www-form-urlencoded instead of as a JSON-encoded body. According to the documentation, in the browser you would use URLSearchParams for this. For example:
const params = new URLSearchParams();
params.append('username', username);
params.append('password', password);
const response = await axios.post('/auth/jwt/login', params);
(That same documentation provides other options as well, to include 3rd party libraries or to POST from NodeJS. The above is specific to in-browser code with no 3rd party libraries.)
The previous solution didn't work for me. This did:
const form = new FormData();
form.append('username', username)
form.append('password', password)
const response = await axios.post('/auth/jwt/login', form,
{ headers: { 'Content-Type': 'multipart/form-data' } }
);
In fact I could just do this:
const login = async (username, password) => {
const response = await axios.post('/auth/jwt/login', {
username,
password
},
{ headers: { 'Content-Type': 'multipart/form-data' } }
);
const {accessToken, user} = response.data;
setSession(accessToken);
dispatch({
type: 'LOGIN',
payload: {
user,
},
});
};

How to programatically call an api in react js

I'm using react js with fetch ,I wanna call an api of refresh token Before my token be expired ,then I calculate the difference between my local date and expire date of the token . I want to call my refresh token api every (expire - localData) - 5 min and update my token in my localStorage.
Is that possible ?
A call my refresh token in Api.js to work globally ,Is that right ?
This is my code but doesn't work like excepting:
Api.js
const duration = localStorage.getItem("duration")
useEffect(() =>{
if(token)
setInterval(() => {
RefreshApi.getRefreshToken().then(res => {
if (typeof res === "string") {
console.log("Error",res)
} else {
var now = moment(new Date(), "DD/MM/YYYY HH:mm:ss");
var expire = moment(new Date(res.expire), "DD/MM/YYYY HH:mm:ss");
var diffTime = moment.duration(expire.diff(now));
localStorage.setItem("token",res.token);
localStorage.setItem("expireDuration",diffTime.asMilliseconds());
localStorage.setItem("expire",res.expire);
}
}).catch(err => {
console.log(err);
})
},(duration - 300000))
},[])
refreshApi.js
getRefreshToken: function () {
return api.get("/refreshToken",{"Authorization": `Bearer ${localStorage.getItem("token")}`}).then(res => {
if (res.ok) {
return res.json();
} else {
return res.text();
}
});
},
Any help please ?
You can do this in different ways.
You can use the fetch API provided by JavaScript
SomeJsxFile.jsx
import { getRefreshToken } from './RefreshToken'
const refreshApi = async () => {
const token = localStorage.getItem("token");
if(token) {
const response = await getRefreshToken(token)
const now = Date.now() // this will return the Epoch time in milliseconds
const expire = Date.now(response.expire)
localStorage.setItem("token", response.token);
localStorage.setItem("expireDuration", now - expire);
localStorage.setItem("expire", response.expire);
return
}
// if dont have the token do something else
}
useEffect(() => {
// 10min = 600000 milleseconds
setInterval(refreshApi(), 600000)
},[])
RefreshToken.js
module.exports = () => ({
getRefreshToken: async (token) => {
return new Promise((resolve, reject) => {
fetch("https://localhost:3000/refreshToken", {
method: "POST",
headers: {
"Authorization": `Bearer ${token}`
},
cache: "default"
})
.then(response => response.json())
.then(responseInJSON => resolve(responseInJSON))
.catch(err => reject(err))
})
}
})
You can use a third-party library, one that is used a lot is the axios.js, you can follow this example:
Api.js
import axios from 'axios'
const api = axios.create({ baseURL: 'http://localhos:3000' })
module.exports = {
api
}
RefreshToken.js
import { api } from './Api'
module.exports = () => ({
getRefreshToken: async (token) => {
return api.get('/refreshToken', {
headers: {
"Authorization": `Bearer ${token}`
}
})
}
})

change api fetch into axios call

i am trying to change the api fetch into axios get method i dont know how to do that
const fetchApi = () => {
const request = getAllActivityData();
request
.api({
params: {
customer,
},
})
i want to call api like this using axios
i have added full code in codesandbox it will be helpfull if u can edit the codesand box and make it working
useEffect(() => {
const config = {
headers: {
Authorization: `token
},
};
axios.get("customer/get-all-activity-data/?customer=22", config)
.then((res) => {
console.log(res.data);
});
code sandbox
https://codesandbox.io/s/upbeat-jasper-2jmri?file=/src/App.js:3137-3298
what i have tryed the data is not showning but there are no error .
i am getting data in postman
https://codesandbox.io/s/gifted-montalcini-j7nv7?file=/src/App.js
Do you mean something like this, using async await...
const axiosCallFn = async () => {
let url = '...'
let config = {
headers: {
token: '...'
}
}
try {
let resp = await axios.get(url, config)
return resp.data
} catch(e) {
throw e
}
}
// import the function into your component and use it like so
axiosCallFn()
.then((data) => {
// your functionality here.
})
.catch(() => {
// your error functionality here.
})
and then you can call your axiosCallFn in your useEffect.

Access session data in Next.js page using withIronSession()

After reading the following post, https://dev.to/chrsgrrtt/easy-user-authentication-with-next-js-18oe and consulting the following question Using next-iron-session's "withIronSession" with Next.JS to perform simple authentication, I am still unable to access the session using req.session.get('user'). Below is my implementation in a Next.js project:
Create a util
import {withIronSession} from 'next-iron-session';
const cookie = {
cookieName: process.env.COOKIE_NAME,
password: process.env.COOKIE_SECRET,
cookieOptions: {secure: process.env.NODE_ENV === 'production'},
};
export const guard = (handler) => {
return withIronSession(handler, cookie);
};
export default cookie;
Create an API endpoint
const zlib = require('zlib');
import cookie from '#/utils/cookie';
const fetch = require('node-fetch');
import {withIronSession} from 'next-iron-session';
export default withIronSession(
async (req, res) => {
if (req.method === 'POST') {
try {
const request = await fetch(
process.env.NEXT_PUBLIC_API_BASE_URL + '/api/login',
{
method: 'post',
body: req.body,
headers: {
'Content-Type': 'application/json',
'Origin': req.headers.host || req.headers.origin,
},
}
);
const response = await request.text();
const {success, data, message} = JSON.parse(response);
// set JWT in session
compressor(data, (x) => req.session.set('user', x));
// persist session value
await req.session.save();
// console.log(req.session.get('user'));
return res.status(201).json({success, message});
} catch (error) {
console.log(error);
}
}
return res.status(404).json('Not found');
},
cookie
);
Access session data in a page
export const getServerSideProps = guard(async (ctx) => {
const {req} = ctx;
const session = req.session.get();
console.log({session});
return {redirect: {destination: '/sign-in', permanent: false}};
});
The above terminal log gives an empty object. Is there something am doing wrong??
Try the following:
export const getServerSideProps = guard(async function ({
req,
res,
query,
}) {
//Assuming you have "user" session object
const user = req.session.get("user");
...
});
Harel

Undefined 404 and React Hook useEffect has a missing dependency

I have a super cute site for flower-fans where you can find a profile of a flower (a mock api), read some info and put a note on each and every flower. Though, I'm not able to make the note stick anymore. So frustrating as it worked a while ago. I have updated the dependencies and also the settings for deploying on Netlify. In Postman I get the same message as in the console, which is not found 404.
I get a message in Terminal that the React Hook useEffect has a missing dependency (flowerId) too.
Down below you'll see the error message and here is a link to my deployed site:
https://flowerinspoapi.netlify.app/
Error message from Console
GET https://flowerinspoapi.netlify.app/flowers/undefined 404
Code from Flowerinfo.js
// Fetching the comments for the flowers
const url = "https://flowers-mock-data.firebaseio.com/comments/TheresaUlwahn"
export const FlowerInfo = () => {
const { flowerId } = useParams()
const [flower, setFlower] = useState([])
const [flowerMessages, setFlowerMessages] = useState([])
const [postedMessage, setPostedMessage] = useState("")
// Fetching the ID of the flowers
useEffect(() => {
fetch(`https://flowers-mock-data.firebaseio.com/flowers/${flowerId}.json`)
.then((res) => res.json())
.then((json) => {
setFlower(json)
})
}, [flowerId])
// Fetching the messages
useEffect(() => {
fetch(`https://flowers-mock-data.firebaseio.com/comments/TheresaUlwahn/${flowerId}.json`)
.then((res) => res.json())
.then((json) => {
console.log('All messages for the flower: ', json)
if (json !== null) {
setFlowerMessages(json)
}
})
}, [postedMessage])
const handleFormSubmit = (flowerId, message) => {
// console.log('POST THIS MESSAGE: ', message, 'FOR THE FLOWER: ', flowerId);
fetch(url + `/${flowerId}/.json`, {
method: "POST",
body: JSON.stringify({ message }),
headers: { "Content-Type": "application/json" }
})
.then(() => {
console.log('posted !')
// window.location.reload();
setPostedMessage(message)
})
.catch(err => console.log("error:", err))
}
var result = Object.keys(flowerMessages).map(function (key) {
return [key, flowerMessages[key]];
});

Resources