I want to fetch a details of the one student I wrote the method for that . It working with postman but not working when i connect it with frontend
frontend controller for fetching student details
export const getStudent = (studentId, token) => {
return fetch(`${API}/student/${studentId}`, {
method: "GET",
headers: {
Accept: "application/json",
Authorization: `Bearer ${token}`,
},
})
.then((response) => {
return response.json();
})
.catch((err) => console.log(err));
};
setting the values
const [student, setStudent] = useState({
fullName: "",
admissionNumber: "",
rollNumber: "",
age: "",
gender: "",
faculty: "",
email: "",
});
const preload = (studentId) => {
getStudent(user._id, token, studentId).then((student) => {
if (student?.error) {
setStudent(console.log(student.error));
} else {
setStudent(student);
}
});
};
useEffect(() => {
preload();
}, []);
backend
exports.getStudent = (req, res) => {
return res.json(req.student);
};
fetching status is ok but response is null
Updated Code
const preload = (studentId) => {
getStudent(studentId, token).then((data) => {
if (data.error) {
setStudent(console.log(data.error));
} else {
setStudent(student);
}
});
};
preload needs only two parameters userid and token
In useEffect it needs to pass the studentId to get the details
useEffect(() => {
preload(match.params.studentId);
}, []);
Related
I've got a client-side app that uses apollo/client and I'have a few server-side function where also use the client to do some light queries and mutations.
I've recently implemented jwt integration and now my server-side calls fail because of what I presume is missing headers.
here is my client setup:
const wsLink = new GraphQLWsLink(
createClient({
url: process.env.API_URL_WS,
webSocketImpl: isNode ? ws : null,
connectionParams: async () => {
const { id_token } = await auth.getSession();
return {
headers: {
Authorization: `Bearer ${id_token}`,
},
};
},
})
);
const authLink = setContext(async (_, { headers }) => {
const { id_token } = await auth.getSession();
return {
headers: {
...headers,
Authorization: `Bearer ${id_token}`,
},
};
});
const httpLink = new HttpLink({
uri: process.env.API_URL_HTTP,
});
const splitLink = split(
({ query, ...rest }) => {
const definition = getMainDefinition(query);
return (
definition.kind === "OperationDefinition" &&
definition.operation === "subscription"
);
},
wsLink,
authLink.concat(httpLink)
);
export const client = new ApolloClient({
link: splitLink,
cache: new InMemoryCache(),
});
and here is how I am using it in the server-side function to make a mutation
await client
.mutate({
mutation: gql`
mutation InsertSubscriptionId(
$id: uuid!
$stripe_subscription_id: String!
) {
update_user_by_pk(
pk_columns: { id: $id }
_set: { stripe_subscription_id: $stripe_subscription_id }
) {
id
}
}
`,
variables: {
id: session.metadata.hasura_user_id,
stripe_subscription_id: session.subscription,
},
context: {
headers: {
Authorization: req.cookies.access_token,
},
},
})
.then((result) => console.log(result))
.catch(console.log);
this call fails even if I use the users access token or apply an admin token for access to the DB.
As a workaround I've resorted to using fetch for this mutation (which works). Any idea why headers are not respected?
My workaround with admin access secret:
fetch(process.env.API_URL_HTTP, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-hasura-admin-secret": process.env.GATSBY_HASURA_ADMIN_SECRET,
},
body: JSON.stringify({
query: `
mutation InsertSubscriptionId(
$id: uuid!
$stripe_subscription_id: String!
) {
update_user_by_pk(
pk_columns: { id: $id }
_set: { stripe_subscription_id: $stripe_subscription_id }
) {
id
}
}
`,
variables: {
id: session.metadata.hasura_user_id,
stripe_subscription_id: session.subscription,
},
}),
})
.then((res) => res.json())
.then((result) => console.log(result));
In this case the session was lost after a few jumps between my app and payment provider. As user can't be authenticated when session is lost, I've resorted to authenticate the admin user for this ssr function
I'm working on the user registration functionality of an application using Typescript and Redux Toolkit. When I make the fetch request to the signup endpoint, a new user is saved to the database I've connected, but I keep entering the catch error block.
export const registerUser = createAsyncThunk(
"user/registerUser",
async (form: { username:string, password:string }, thunkAPI) => {
try {
const response = await fetch('/api/auth/signup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userInfo: {
username: form.username,
password: form.password
}
}),
});
if (response.status === 200) return 200;
else return 400;
} catch (e) {
console.log('Error')
}
}
);
I've tried logging the response to the console a number of ways
const data = await response.json() console.log(data)
But have had no luck. I think this is an error with how I've done my fetch request using createAsyncThunk but haven't been able to figure out what I've missed.
This is the code for the initial state and slice:
interface UserState {
userProfile: {
id: number | null;
},
registration: {
status: 'loaded' | 'loading'
}
}
const initialState : UserState = {
userProfile: {
id: null,
},
registration: {
status: 'loaded'
}
};
export const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
},
extraReducers: (builder) => {
builder.addCase(registerUser.fulfilled, (state) => { state.registration.status = 'loaded' }),
builder.addCase(registerUser.rejected, (state) => { state.registration.status = 'loaded' }),
builder.addCase(registerUser.pending, (state) => { state.registration.status = 'loading' })
}
})
And here is the code for the function where the action is dispatched on the UI
const handleRegister= async () => {
if (!username) return alert('Username field was left empty');
if (!password) return alert('Password field was left empty');
const {payload} : any = await dispatch(registerUser({ username: username, password: password}));
if (payload === 200) {
alert('Successfully registered. Redirecting to dashboard');
return navigate('/dashboard');
} else { return alert('User creation unsuccessful'); }
}
Appreciate any help as I've looked through many other posts but haven't been able to resolve my issue.
I have this authFetch function that fetches the token and updates it in mongo and token variable.
const authFetch = async () => {
let authCollection = client.db("WheelPros_data").collection("auth");
TokenFromDB = await authCollection.find({ _id: 1 }).toArray();
({ accessToken: token, time: lastFetchedAuth } = TokenFromDB[0] || [{ accessToken: null, time: 0 }])
// console.log(new Date().getTime() / 1000 - lastFetchedAuth)
let axiosConfig = {
headers: {
"Content-Type": "application/json",
accept: "application/json",
},
};
await axios({
method: "POST",
data: {
userName: process.env.WHEELPROS_USERNAME,
password: process.env.PASSWORD,
},
url: `${process.env.PROD_API_URL}/auth/v1/authorize`,
axiosConfig,
})
.then(async (res) => {
const { accessToken } = res.data;
authCollection.updateOne(
{ _id: 1 },
{
$set: {
accessToken: accessToken,
time: new Date().getTime() / 1000,
Date: new Date(),
},
}, {
upsert: true
}
);
console.log("newAccessToken : ", accessToken)
token = await accessToken
console.log("inside token var = ", token)
console.log("------------------Auth Updated------------------");
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
});
}
await authFetch()
// console.log("ourside token var = ", token)
setInterval(authFetch, 3590000)
Problem arises when i call another async function to fetch the submodels. After 1 hour the token expires and that is why we have setInterval function to update the token but it does not update the token and i get hit with the 403 error
Below is the modelFetch function
const fetchSubmodels = async () => {
const modelDataFromDB = await collection
.find({ modelData: { $exists: true } })
.toArray();
console.log(modelDataFromDB.length)
modelDataFromDB.forEach(async (modeldata) => {
// await fetchToken().catch(console.error)
let dataSearch = modeldata.modelData.split(';')
await axios
.get(
`${process.env.PROD_API_URL}/${dataSearch[0]}/makes/${dataSearch[1]}/models/${dataSearch[2]}/submodels`,
{
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
}
)
.then(async function ({ data }) {
await collection.updateOne(
{ modelData: modeldata.modelData },
{
$set: {
submodels: data
},
}
);
// handle success
console.log(`pushing the submodels ${data} to ${modeldata.modelData} `)
})
.catch(async function (error) {
// handle error
console.log(error);
})
})
}
await fetchSubmodels()
clearInterval(authFetch)
Any insights would be helpful!
Like array.map, array.forEach does not await the result of the function that it calls. In your case, this means that the axios.get statements for each entry in modelDataFromDB send out all requests synchronously, while token still has its original value. (Therefore they should never lead to 403, if they reach the backend in time.)
What's more, fetchSubmodels does not await anything and therefore resolves after all these requests have been sent out. At that point in time await fetchSubmodels() is completed, therefore clearInterval(authFetch) is executed almost immediately, and the setInterval has no effect.
While this does not yet explain the 403 responses, it is certainly not what you intended.
If you replace
modelDataFromDB.forEach(async (modeldata) => {
...
})
with
for (var modeldata of modelDataFromDB) {
...
}
the requests will be sent consecutively, and fetchSubmodels will await the response of the last request.
I am trying to decrease the quantity, which I have to change on mongodb database, also I need to show it in body. I set a button called delivered which will decrease the quantity value by 1 . but when I click on the delivered button suddenly nodemon index.js cmd crashed. it says"MongoInvalidArgumentError: Update document requires atomic operators"
//Client side:
const handleQuantity = (quantity) => {
const newQuantity = Number(quantity) - 1;
// console.log(newQuantity);
fetch(`http://localhost:5000/inventory/${itemsId}`, {
method: "PUT",
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({ newQuantity })
})
.then(res => res.json())
.then(data => console.log(data))
}
//server side:
app.put('/inventory/:id', async (req, res) => {
const id = req.params.id;
const property = req.body;
const query = { _id: ObjectId(id) };
const options = { upsert: true };
const updateDoc = {
$set: {
quantity: property.newQuantity
}
};
const result = await inventoryCollection.updateOne(query, options, updateDoc);
res.send(result)
})```
Client side:
const handleQuantity = (quantity) => {
const newQuantity = parseInt(quantity) - 1;
// console.log(newQuantity);
fetch(`http://localhost:5000/inventory/${itemsId}`, {
method: "PUT",
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({ newQuantity })
})
.then(res => res.json())
.then(data => console.log(data))
}
I'm successfully authenticating with the server, sending my graphql request and receiving a response. However the response isn't quite right.
This is just a simple nodejs, axios, graphql situation. I can get a correct respose via postman or curl but not with node. I've tried fetch as well to no avail. Am I doing something wrong? This is for the producthunt api, the api explorer is located at here
require('dotenv').config()
const axios = require("axios");
const PH_KEY = process.env.PH_KEY;
const PH_SECRET = process.env.PH_SECRET;
const BASE_URL = process.env.BASE_URL;
const AUTH_URL = process.env.AUTH_URL;
const GRAPHQL_URL = process.env.GRAPHQL_URL;
const PH = axios.create({
baseURL: BASE_URL,
responseType: 'json',
headers: {
// 'Accept': 'application/json, text/plain, gzip, deflate, */*',
'Content-Type': 'application/json'
},
})
let TOKEN = 'Bearer '
const getAuth = async () => {
return await PH({
url: AUTH_URL,
method: "post",
data: {
client_id: `${PH_KEY}`,
client_secret: `${PH_SECRET}`,
grant_type: "client_credentials"
}
})
.then((res) => {
console.log('auth status ', res.status)
return res.data.access_token
})
.then((res) => {
TOKEN += res
console.log(TOKEN)
})
.catch((err) => {
console.log(err)
})
}
const getHunt = async () => {
await getAuth()
PH.defaults.headers.common['Authorization'] = TOKEN
return await PH({
url: GRAPHQL_URL,
method: 'post',
data:
{
query: `
query posts {
posts(order: RANKING, first: 1) {
edges {
node {
name
votesCount
user {
name
}
createdAt
}
}
}
}
`
}
})
.then((res) => {return res})
.then((res) => {
console.log(res.data)
return res.data
})
.catch((err) => {
console.log(err)
})
}
const Main = async () => {
await getHunt()
}
Main()
This is the output I receive in node:
[Running] node "/Users/fireinjun/Work/YAC/yac-ph-tophuntfunction/app.js"
auth status 200
Bearer #################################################
{ data: { posts: { edges: [Array] } } }
Here's what I'm expecting:
{
"data": {
"posts": {
"edges": [
{
"node": {
"name": "Trends by The Hustle",
"votesCount": 125,
"user": {
"name": "Jack Smith"
},
"createdAt": "2019-06-04T07:01:00Z"
}
}
]
}
}
}
I was accessing the data incorrectly! Apparently I needed to see the res.data.data.posts.edges[0]