Error 401 Unauthorized in Axios in React JS - reactjs

I was trying to post a comment through Axios. But I am getting the 401 error, even though I have passed the header with the Authorization token. I don't know what is causing this error.
Please Help . My boss is yelling at me :) (I am a junior developer).
const handleSubmit = async (e: any) => {
e.preventDefault();
const finalComment = { comment };
try {
const response = await axios.post(
`${TEST_API_URL}/user/proposal/comments/admin/create`,
finalComment,
{
withCredentials: true,
headers: {
Authorization: `${localStorage.getItem('access_token')}`,
},
}
)
console.log(response);
} catch (error) {
console.log(error);
}
}

Related

Request working correctly on Postman but gives a 404 error when I process it via React App

I have been trying to working with Github Gists API, specifically the "Star a Gist"functionality but I am noticing a strange behavior when I send a request via my React app.
Here's the code for the request:
const starNote = async (noteId, token) => {
const config = {
headers: {
Authorization: `Bearer ${token}`,
"Content-Length": "0",
},
}
try {
const response = await axios.put(`${API_URL}/${noteId}/star`, config, {
noteId: noteId,
})
console.log("request sent")
if (response.status === 204) {
console.log("working", response)
return true
}
} catch (error) {
if (error.response.status === 404) {
console.log(error)
}
}
}
And here's the code for the slice function:
export const starNote = createAsyncThunk(
"notes/starNote",
async (noteId, thunkAPI) => {
try {
const token = thunkAPI.getState().auth.user.accessToken
return await notesService.starNote(noteId, token)
} catch (error) {
const message =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString()
return thunkAPI.rejectWithValue(message)
}
}
)
The action gets triggered correctly but the request doesn't go through the:
console.log("request sent")
part and goes straight to the error. If you send a GET request, it gives a 404 error if you haven't starred a gist. But for the PUT request, why does it go straight to the error and not send the request. If i try the same with Postman it works correctly and returns a
response.status: 204
What am I doing wrong here?
Okay so what I did was insert this in the PUT request:
{ noteId: noteId }
And it worked.
Here's the complete code of the call:
const starNote = async (noteId, token) => {
const config = {
headers: {
Authorization: `Bearer ${token}`,
"Content-Length": "0",
},
}
try {
const response = await axios.put(
`${API_URL}/${noteId}/star`,
{ noteId: noteId },
config
)
console.log("request sent")
if (response.status === 204) {
console.log("working", response)
return true
}
} catch (error) {
if (error.response.status === 404) {
console.log(error)
}
}
}
I am still not sure why it's necessary but this is what it needed.

Error response when sending data to prisma

I am working on a crud app using prisma and postgres. Currently I am getting error response when submitting data via POST method. Can someone please tell me what I am doing wrong?
api:
import { NextApiRequest, NextApiResponse } from "next";
import { prisma } from "../../lib/prisma";
const {title, content} = req.body
try {
await prisma.note.create({
data: {
title,
content
}
})
res.status(200).json({message: 'Note Created'})
} catch (error) {
res.status(500).json({error: "Something went wrong"})
Fetch function:
async function create(data: FormData) {
try{
fetch('http://localhost:3000/api/create', {
body: JSON.stringify(data),
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
}).then(() =>{setForm({title: '',content: '',id: '',
})
})
}catch(err){
console.log(err)
}
}
Handle Submit:
const handleSubmit = async (data: FormData) => {
try {
create(data)
} catch (error) {
console.log(error);
}
}
In your create function, you are calling JSON.stringify on an instance of FormData. This will result in an empty object, even if the FormData contains the correct values.
Object.fromEntries(data.entries()) will give you a plain object of the FormData entries, then you can call JSON.stringify on the result of that operation.

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.

NEXT.js API route wont accept POST requests

I have a Next.js API route set up at "pages/api/contact". When I process a GET request or navigate to localhost:3000/api/contact I can see the api is working. However, whenever I try to process a get request to this API route nothing happens. I have tried using axios and fetch but nothing seems to work for post request. See below. Any help would be greatly appreciated.
called from a component when a button is clicked
const handleClick = async (e) => {
e.preventDefault();
console.log("in handleSubmit");
try {
const res = await axios.post(
"http://localhost:3000/api/contact",
{
firstName,
lastName,
email,
},
{
headers: {
"Content-Type": "application/json",
},
},
console.log(res) //this comes back undefined
);
} catch (e) {}
};
in pages/api/contact
export default async function sendEmail(req, res) {
const { firstName, lastName, email } = req.body;
console.log(req.method);
if (req.method === "POST") {
return res.status(200).json({
message: "This is in post",
});
} else {
return res.status(200).json({
message: "This is not a post",
});
}
}
I think it syntax error
try {
const res = await axios.post(
"http://localhost:3000/api/contact",
{
firstName,
lastName,
email,
},
{
headers: {
"Content-Type": "application/json",
},
},
);
console.log(res) //check now
} catch (e) {}

Unable to fetch Data in Netlify Dev Proxy (React)

I've been having CORS error when deploying my app so I decided to try out Netlify Dev.
I followed all steps of the written tutorials but I keep getting errors without being able to identify whats wrong. I haven't even deployed it yet and right now I am having the 403 error, before this was the 500 internal server error.
Please let me know if you notice any obvious mistake on my part.
Here's the node-fetch code:
const fetch = require("node-fetch");
exports.handler = async function () {
const headers = {
"x-api-key": process.env.REACT_APP_MY_API_KEY,
"content-type": "application/json",
};
try {
const response = await fetch("https://api.crimeometer.com", { headers });
if (!response.ok) {
return { statusCode: response.status, body: response.statusText };
}
const data = await response.json();
return {
statusCode: 200,
body: JSON.stringify(data),
};
} catch (err) {
console.log(err);
return {
statusCode: 500,
body: JSON.stringify({ msg: err.message }),
};
}
};
Here's the frontend of my app (with the relevant code):
const initializeApp = useCallback(() => {
async function fetchData() {
try {
let req = new Request(
`./.netlify/functions/node-fetch?lat=${lat}&lon=${lon}&distance=10km&datetime_ini=${newdateyear}&datetime_end=${newdatenow}&page=1`);
const res = await fetch(req);
const info = await res.json();
setCrimes(info.incidents);
} catch (err) {
console.log(err);
}
}
}, [submit, lat, lon]);
useEffect(() => {
initializeApp();
}, [initializeApp]);
This is the error in my console:
This is where i am trying to fetch data from:
https://api.crimeometer.com/v1/incidents/raw-data?lat=${lat}&lon=${lon}&distance=10km&datetime_ini=${newdateyear}&datetime_end=${newdatenow}&page=1
It requires two headers to be set on frontend, which I have done in the netlify function
The API key is currently being added to the React side, where it sets a header and makes a call to the netlify function. But the API key is actually required at the netlify function to request the third party API.
So you have to move the request header from React to Netlify function with something like:
const headers = {
'x-api-key': API_KEY,
'content-type': 'application/json',
}
const response = await fetch(
"https://api.crimeometer.com/v1/incidents/raw-data",
{ headers }
);

Resources