How do I use Axios GET Params using a search input - axios

I'm trying to send GET request and I also want to fetch the data using the search input. So I have used Params but it is not working ,
here's my code :
// setFetching(true)
let url = `${TEST_API_URL}/teammember/getAll`
try {
const posts: any = await axios.get(`${url}`, {
withCredentials: true,
headers: {
Authorization: `${localStorage.getItem('access_token')}`,
},
params: {
search
},
})
console.log(posts.data.Data)
setPosts(posts.data.Data)
} catch (error: any) {
toast.error('Something went wrong')
}
// setFetching(false)
}, [search])
useEffect(() => {
async function fetchData() {
await fetchFunction()
}
void fetchData()
}, [fetchFunction])```

I recommend you to do like this.
// setFetching(true)
let url = `${TEST_API_URL}/teammember/getAll`
try {
const posts: any = await axios.get(`${url}?search=${search}`, {
withCredentials: true,
headers: {
Authorization: `${localStorage.getItem('access_token')}`,
}
})
console.log(posts.data.Data)
setPosts(posts.data.Data)
} catch (error: any) {
toast.error('Something went wrong')
}
// setFetching(false)
}, [search])
useEffect(() => {
async function fetchData() {
await fetchFunction()
}
void fetchData()
}, [fetchFunction])```

Related

unstable_getServerSession to secure apis (nextAuth)

i need to secure the API so that only authorized user can access them. I followed the documentation in this link https://next-auth.js.org/tutorials/securing-pages-and-api-routes#securing-api-routes but apparently I am not retrieving the session.
I am able to console.log the authOptions but if I try to console log the session (and I am logged in), it logs "null"
This is the code
pages/api/profile.js
import prisma from "../../../lib/prisma";
import { unstable_getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";
export default async function handler(req, res) {
const session = await unstable_getServerSession(req, res, authOptions);
console.log("SESSION", session); // this logs "null"
if (!session) {
return res.status(401).json("Not authorized");
}
try {
const user = await prisma.user.findUnique({
where: { email: session.user.email },
});
return res.status(200).json(user);
} catch (error) {
console.error(error);
return res
.status(503)
.json(
"Our server is not able to process the request at the moment, please try again later!"
);
}
pages/api/auth/[...nextauth].js
import NextAuth from "next-auth";
import CognitoProvider from "next-auth/providers/cognito";
import prisma from "../../../lib/prisma";
export const authOptions = {
providers: [
CognitoProvider({
clientId: process.env.CLIENTID_NEXTAUTH,
issuer: process.env.COGNITO_ISSUER,
clientSecret: process.env.CLIENTSECRET_NEXTAUTH,
}),
],
session: {
strategy: "jwt",
maxAge: 30 * 24 * 60 * 60,
updateAge: 24 * 60 * 60,
},
callbacks: {
async jwt({ token, account }) {
if (account) {
token.accessToken = account.access_token;
}
return token;
},
async session({ session, token }) {
const user = await prisma.user.findUnique({
where: { email: session?.user?.email },
});
if (!user) throw new Error("User not found in the database.");
const mySession = {
...session,
accessToken: token.accessToken,
email: user.email,
};
return mySession;
},
},
};
export default NextAuth(authOptions);
pages/dashboard/index.js
import axios from "axios";
import React, { useState } from "react";
import { getSession, useSession } from "next-auth/react";
const Dashboard = (props) => {
let { data: session, status } = useSession();
if (status === "loading") {
return <p>Loading...</p>;
}
if (status === "unauthenticated") {
window.location.reload();
}
return (
<p>
{props.userInfo.name}
</p>
);
};
export default Dashboard;
export async function getServerSideProps(context) {
const session = await getSession(context);
if (!session) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
}
console.log("SESSION IN INDEX", session); // this logs the session
const userInfo = await axios.get(
`${process.env.BASE_URL}/api/profile?email=${session.email}`
);
return {
props: {
session,
userInfo: userInfo.data ? userInfo.data : null,
},
};
}
so when I login, I can see the SESSION in INDEX but when I hit the api/profile, the session from unstable_getServerSession is null, so I canno see nothing in the dashboard
resolved:
when calling the api you need to pass the headers, for example in the dashboard/index.js
const userInfo = await axios.get(
`${process.env.BASE_URL}/api/profiles/profile?email=${session.email}`,
{
withCredentials: true,
headers: {
Cookie: context.req.headers.cookie,
},
}
);
while in the API endpoint
import { getServerSession, getSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";
export default async function handler(req, res) {
const session = await getServerSession(req, res, authOptions);
console.log("SESSION", session);
//your code
}

Req. query doesn't pass

I'm trying to pull data from a document containing a logged-in user from the MongoDB database. However, req. the query doesn't seem to pass.
case "GET": {
const { userName } = req.query;
const users = await db
.collection("USERS")
.find({ user: { $in: [userName] } })
.toArray();
res.json(users);
break;
}
export async function getStaticProps() {
const res = await fetch(`http://localhost:3000/api/usersAPI`, {
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
let users = await res.json();
return {
props: { users },
};
}

IOWebSocketChannel Flutter & GraphQL Apollo

I'm having an issue connecting to a GraphQL endpoint using Web-sockets.
The issues are noted in the comments. I cannot get this working. It works on the browser (separate test application) so the server is fine.
IOWebSocketChannel? _channel;
StreamSubscription? _getSubscription;
connectToWebsocket(BuildContext context) {
// Nothing to listen to. Auth users only.
final auth = authProviderRead(context);
if (auth.modelUser == null) {
return;
}
_channel?.sink.close();
_getSubscription?.cancel();
final headers = {
"Authorization": auth.jwt ?? "",
"Content-Type": "application/json",
};
_channel = IOWebSocketChannel.connect(
Uri.parse(getWebStockUrl()),
headers: headers,
protocols: ["graphql-ws"],
);
// Fails: Just fires "onDone"
// _channel?.sink.add(jsonEncode({"data": subscriptionQuery}));
// Fails with {"type":"connection_error","payload":{"message":"Cannot read properties of undefined (reading 'Authorization')"}}
// _channel?.sink.add(json.encode({"type": "connection_init"}));
// Fails with {"type":"error","payload":{"message":"Invalid message type!"}}
// _channel?.sink.add(jsonEncode(
// {
// "type": "data",
// "query": subscriptionQuery,
// },
// ));
_getSubscription = _channel!.stream.listen((message) {
// Is never fired?
if (kDebugMode) {
print("Got live message");
print(message);
}
// channel!.sink.add('received!');
// channel!.sink.close();
})
..onData((data) {
if (kDebugMode) {
print("onData - WebSocket");
print(data);
}
})
..onDone(() {
if (kDebugMode) {
print("onDone - WebSocket");
}
})
..onError((e) {
if (kDebugMode) {
print("onError - WebSocket");
print(e);
}
});
}
const subscriptionQuery = r'''
subscription Subscription {
gotChatMessage {
messageResults {
message {
markdown
}
}
}
}
''';
I figure it out, there are some additional things that it requires.
From https://github.com/apollographql/subscriptions-transport-ws/blob/master/src/message-types.ts
_channel?.sink.add(jsonEncode({
"type": "connection_init",
"payload": {"Authorization": auth.jwt}
}));
_channel?.sink.add(jsonEncode({
"type": "start",
"payload": {"query": subscriptionQuery}
}));

capacitor community/http handle errors

I often use Axios to perform requests in my applications, however due to incompatibility with iphone, I had to use the capacitor-community/http library, however the try catch blocks are always returning success, even if there was an error in the request. How can I handle errors using this library?
try {
await Requester.auth.public.login(formData);
this.$store.dispatch('login', user);
this.$root.$emit('showToast', {
text: 'Seja bem vindo!',
color: 'success',
});
this.$router.push({ name: 'Cotacao' });
} catch (err) {
this.$root.$emit('showToast', {
text: err.response?.data ?? err.toString(),
color: 'error',
});
} finally {
this.loading.submitForm = false;
}
},
My request
const login = async (formData: AuthLoginFormData): Promise<User> => {
const res: HttpResponse = await Http.post({
url: `${BASE_URL}public/auth/login`,
headers: {
'Content-Type': 'application/json',
},
data: formData,
webFetchExtra: {
credentials: 'include',
},
});
return res.data;
};
Install Latest https://github.com/capacitor-community/http plugin
use function
public async login(formData: AuthLoginFormData){
let options = {
url: `${BASE_URL}public/auth/login`,
headers: {
'Content-Type': 'application/json',
},
data: formData,
webFetchExtra: {
credentials: 'include',
}
};
let response: HttpResponse = await Http.request(options);
if (response.status === 200) {
return Promise.resolve(res);
}
return Promise.reject(response.data);
}

Empty data in response with axios and vuex

When I send this patch request with axios, the backend receives the data, but response.data comes back empty. Please and thanks!
// ACTION IN VUEX STORE
async updateMe({ commit }, payload) {
let id = localStorage.getItem('userId');
let user = { name: payload.name, email: payload.email, id: id };
try {
const response = await axios.patch(
`http://localhost:3000/api/v1/users/updateMe`,
user
);
commit('setUpdatedUser', response.data);
} catch (err) {
console.log(err);
}
}
// CONTROLLER
exports.updateMe = catchAsync(async (req, res, next) => {
const updatedUser = await User.findByIdAndUpdate(
req.body.id,
{
name: req.body.name,
email: req.body.email
},
{ new: true, runValidators: true }
);
res.status(204).json({ data: updatedUser });
});
204 is a No Content response code.