I am trying to use axios in nodejs typescript project and during the build it is throwing an error abortSignal any fix for this issue appreciate the help
index.ts
export async function getAccessToken(apiConfig: any) {
const req = {
grant_type: apiConfig.authOptions.body.grant_type,
client_id: apiConfig.authOptions.credentials.clientId,
client_secret: apiConfig.authOptions.credentials.clientSecret,
scope: apiConfig.authOptions.body.scope
};
const headers = {
"Content-Type": "application/x-www-form-urlencoded",
"appName": "Blink"
};
try {
const resp: AxiosResponse = await axios.post('https://test.com//auth/oauth2/token',
req, { headers });
console.log(resp.data);
} catch (err) {
// Handle Error Here
console.error(err);
}
}
Error
node_modules/axios/index.d.ts(93,12): error TS2304: Cannot find name 'AbortSignal'.
Package.json
"axios": "^0.24.0",
Try providing abortController signal in the axios parameter:
const abortController=new AbortController;
const resp: AxiosResponse = await axios.post(
'https://test.com//auth/oauth2/token',
req,
{ headers },
signal:abortController.signal
);
Related
I'm currently building an app using React Native on the frontend and Node.js together with express on the backend.
I have two axios instances, one of which I call the main server and the other the authentication server. With both instances all normal server calls outside of the following file are working expect this one. I'm currently localhosting both servers.
My frontend looks like this:
import axios from 'axios';
import AsyncStorage from '#react-native-async-storage/async-storage';
const BASE_URL = 'URL_PLACEHOLDER'; // <- IP Address of my computer
export const instanceMain = axios.create({
baseURL: `${BASE_URL}:3000`,
timeout: 1000,
});
export const instanceAuth = axios.create({
baseURL: `${BASE_URL}:4000`,
});
// Interception to check if a token refresh is needed
instanceMain.interceptors.request.use(async function (response) {
const accessToken = await AsyncStorage.getItem('accessToken');
const refreshToken = await AsyncStorage.getItem('refreshToken');
await instanceAuth
.post(`/token`, {
accessToken: accessToken,
refreshToken: refreshToken,
})
.then((res) => {
AsyncStorage.setItem('accessToken', res.data.accessToken);
AsyncStorage.setItem('refreshToken', res.data.refreshToken);
})
.catch((error) => {
console.log(error);
});
return response;
});
My backend of the post axios is trying to make looks like this:
app.post('/token', async (req, res) => {
try {
const accessToken = req.body.accessToken;
const refreshToken = req.body.refreshToken;
if (accessToken == null || accessToken == undefined)
return res.sendStatus(401);
// Verifying AccessToken
jwt.verify(accessToken, process.env.ACCESS_TOKEN_SECRET, (error) => {
// If it is expired this should be executed. I think I'm probably handling this
// the wrong way, but this was the only way I could think of.
if (error) {
// tokenDB is an in-storage json database containing all active refresh tokens
tokenDB.read();
tokenDB.data ||= { tokens: [] };
if (refreshToken == null) return res.sendStatus(401);
// Checking if tokenDB does not contain the refresh token, if so, return 403
if (!tokenDB.data.tokens.includes(refreshToken)) {
return res.sendStatus(403);
}
// Verifying RefreshToken
jwt.verify(
refreshToken,
process.env.REFRESH_TOKEN_SECRET,
(error, account) => {
// Deleting iat from account, otherwise the new tokens would be the same
// as before
delete account.iat;
if (error) return res.sendStatus(403);
// Generating new Tokens
const newAccessToken = generateAccessToken(account);
const newRefreshToken = generateRefreshToken(account);
// Removing old refreshToken from tokenDB and push newRefreshToken to it
tokenDB.data.tokens = tokenDB.data.tokens.filter(
(token) => token !== refreshToken
);
tokenDB.data.tokens.push(newRefreshToken);
// Result: new Access and Refresh token
res.json({
accessToken: newAccessToken,
refreshToken: newRefreshToken,
});
tokenDB.write();
}
);
} else {
return res.sendStatus(100);
}
});
} catch (error) {
console.error(error);
}
});
The error message simply says [AxiosError: Network Error]. error.config gives back the following, but I can't do much with it.
{"adapter": [Function xhrAdapter], "baseURL": "IP_PLACEHOLDER:4000", "data": "{\"accessToken\":\"ACCESS_TOKEN_PLACEHOLDER",\"refreshToken\":\"REFRESH_TOKEN_PLACEHOLDER"}", "env": {"Blob": [Function Blob], "FormData": [Function FormData]}, "headers": {"Accept": "application/json, text/plain, */*", "Content-Type": "application/json"}, "maxBodyLength": -1, "maxContentLength": -1, "method": "post", "timeout": 0, "transformRequest": [[Function transformRequest]], "transformResponse": [[Function transformResponse]], "transitional": {"clarifyTimeoutError": false, "forcedJSONParsing": true, "silentJSONParsing": true}, "url": "/token", "validateStatus": [Function validateStatus], "xsrfCookieName": "XSRF-TOKEN", "xsrfHeaderName": "X-XSRF-TOKEN"}
I hope I can find some help here, Thanks.
Use redux and proper async/await function to use. Otherwise, Axios return an error.
enter link description here
recommendation
use better only node.js and express ,axios isn't necesary because express is same
I am following the stripe docs about validating webhooks and despite I do everything as they do i keep getting 400 error. BTW in the docs here https://stripe.com/docs/webhooks/signatures they don't return from the catch blok but here https://stripe.com/docs/webhooks/quickstart they do, so I assyme that the correct option is to return from it? And back to my main problem I have no idea what am I missing here this is my code:
import { NextApiHandler } from "next";
import { Stripe } from "stripe";
import { apolloClient } from "../../graphql/apolloClient";
import {
UpdateOrderDocument,
UpdateOrderMutation,
UpdateOrderMutationVariables,
} from "../../generated/graphql";
import type { StripeWebhookEvents } from "../../stripeEvents";
const stripeWebhookHandler: NextApiHandler = (req, res) => {
const webhookSignature = req.headers["stripe-signature"];
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
const stripeSecret = process.env.STRIPE_SECRET_KEY;
if (!stripeSecret || !webhookSignature || !webhookSecret) {
return res.status(500).json({ error: "Stripe credential not provided" });
}
const stripe = new Stripe(stripeSecret, { apiVersion: "2020-08-27" });
let event;
try {
event = stripe.webhooks.constructEvent(
req.body,
webhookSignature,
webhookSecret
) as StripeWebhookEvents;
} catch (err: unknown) {
return res
.status(400)
.send(`Webhook Error: ${err instanceof Error && err.message}`);
}
switch (event.type) {
case "charge.succeeded":
apolloClient.mutate<UpdateOrderMutation, UpdateOrderMutationVariables>({
mutation: UpdateOrderDocument,
variables: {
id: {
id: event.data.object.metadata.cartId,
},
data: {
stripeCheckoutId: event.data.object.id,
email: event.data.object.receipt_email,
},
},
});
break;
}
res.status(204).end();
};
export default stripeWebhookHandler;
and I thought that maybe next has maybe different shape of req.headers or req.body and I am not sure abouut req body, headers seem to be in tact however. At least the signature seems to be extracted correctly. Dhose are test data of course:
{
webhookSignature: 't=1658224240,v1=a3f574b3e6c3a02eb86308e5e43f3d0a96664098ee5dd58859fc94e96693fc50,v0=ef29de87716d9d318d6ad960f028fd5960618c853ff686bd44e261aaa2368f3b',
webhookSecret: 'whsec_0d8a54d09bf221f7c5c77ca7a3fca4b988ccd9e49d8a31d7c91f854025503fe4',
stripeSecret: 'sk_test_51Kuvp4KsMpogemXo9vUcgihi1vK4dlof76OL4EcYhmVgN8r81tl7r0rSsqWgOtXxYnZPJlo6S2KA0gFWZmyBQIbS00ABzicwum',
headers: {
host: 'localhost:3000',
'user-agent': 'Stripe/1.0 (+https://stripe.com/docs/webhooks)',
'content-length': '2818',
accept: '*/*; q=0.5, application/xml',
'cache-control': 'no-cache',
'content-type': 'application/json; charset=utf-8',
'stripe-signature': 't=1658224240,v1=a3f574b3e6c3a02eb86308e5e43f3d0a96664098ee5dd58859fc94e96693fc50,v0=ef29de87716d9d318d6ad960f028fd5960618c853ff686bd44e261aaa2368f3b',
'accept-encoding': 'gzip'
}
is there something I do incorrectly here? Thanks a lot
I'm having trouble with this code because token is returning undefined.
In my frontend:
export const fetchUser = async (token: any) => {
const res = await axios.post('/user/getuser', {
headers: {Authorization : token}
});
return res;
};
And in my middleware is:
const jwt = require('jsonwebtoken');
import {Request, Response, NextFunction} from 'express';
const auth = (req: Request | any, res: Response, next: NextFunction) => {
try {
const token = req.headers('Authorization');
console.log(token);
if(!token) return res.status(400).json({msg: 'Invalid Authentication.'});
jwt.verify(token, process.env.ACCESS_TOKEN as string, (err: any, user: any) => {
if(err) return res.status(400).json({msg: "Invalid Authentication token"})
req.user = user;
next();
});
} catch (error: any) {
return res.status(500).json({msg: error.message});
}
}
module.exports = auth;
I've tested it in Postman and there's no problem, however there's a problem when I make requests from my frontend.
You can try using
req.headers.authorization
This way you can get the auth object from the request header and get the value from it.
I did the as above and it worked well with no problem, try that please. I
I have set up JWT to be set in localstorage whenever someone logins or registers. And it works, I can see the token in localstorage. But when I set the token in the headers with axios, node.js in the backend can`t find the token. Like it does not exists. I have checked it in the front end, I get logs of the token in the headers. And also when I request from postman it works. Here is the code.
setAuthToken function = {
const instance = axios.create({
baseURL: "https://localhost:5000",
});
if (token) {
instance.defaults.headers.common["x-auth-token"] = `${token}`;
console.log(instance.defaults.headers.common["x-auth-token"]);
} else {
delete instance.defaults.headers.common["x-auth-token"];
}
}
const loadUser = async () => {
if (localStorage.token) setAuthToken(localStorage.token);
console.log(localStorage.token);
try {
const res = await axios.get("/api/users");
console.log(res);
dispatch({ type: USER_LOADED, payload: res.data });
} catch (err) {
console.log(err.response.data.msg);
dispatch({ type: AUTH_ERROR });
}
The request comes to the await axios statement and goes to catch so error is in the request.
Here is the backend code
// Get current user
router.get("/", auth, async (req, res) => {
try {
const user = await User.findById(req.user.id);
res.status(200).json({ user });
} catch (err) {
console.log(err);
res.status(500).json({ msg: `Server Error` });
}
});
auth middleware function here = {
const token = req.headers["x-auth-token"];
console.log(token, "token in auth.js");
console.log(req.headers, "req.header");
if (!token) {
return res.status(401).json({ msg: `Access denied.` });
}
try {
const decoded = jwt.verify(token, config.get("jwtSecret"));
req.user = decoded.user;
next();
} catch (err) {
res.status(401).json({ msg: `Token is not valid` });
}
}
I`m new to backend develoment and axios. Can someone help me please. Thank you
Here are the console.logs
Logs
Logs
Little update, it looks like there is a problem with proxy, I am using my own backend api, and also movie data base api. So maybe thats why I cant set headers? Here are new logs:
config: Object { url: "/api/users", method: "get", timeout: 0, … }
data: "Proxy error: Could not proxy request /api/users from localhost:3000 to http://localhost:5000/ (ECONNREFUSED)."
headers: Object { connection: "keep-alive", date: "Wed, 05 May 2021 13:18:05 GMT", "keep-alive": "timeout=5", … }
request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }
status: 500
statusText: "Internal Server Error
I think the issue is because you are setting you are setting up your instance wrongly
set up your instance in a new file config.js -
import Axios from 'axios';
const baseURL = "http://localhost:5000";
const axiosInstance = Axios.create({
baseURL: baseURL,
});
axiosInstance.interceptors.request.use(
function (config) {
const token = localStorage.getItem('token');
if (token) {
config.headers['Authorization'] = 'Bearer ' + token;
}
return config;
},
function (error) {
return Promise.reject(error);
}
);
export default axiosInstance;
now when making any api request instead of using axios use axiosInstance eg-
axiosInstance.get('/something').then(res => console.log(res)).catch(err => console.log(err))
I'm trying to switch from request.js to got.js. I expect to see the got.js implementation authenticate similarly to how the request.js library does. But, instead, I get the following error.
auth no longer supported. Replaced by username and password.
There is no mention of bearer tokens on the docs page.
So how do I authenticate my request using bearer tokens using got.js? Or what am I doing wrong?
Current code: request.js, working
const request = require('request');
const module.exports = config => {
const options = {
auth: {
bearer: config.secret,
},
};
const result = await new Promise(( resolve, reject, ) => {
request.get( url, options, ( error, response, body, ) => {
...
New code: got.js, throws error
const got = require('got');
module.exports = async config => {
const options = {
auth: {
bearer: config.secret,
},
};
const result = await got(url, options);
...
}
This should be worked, if I'm not wrong
let token = 'your token'
const options = {
headers: {
'Authorization': `Bearer ${token}`
}
};
worked for me !!
router.get('/product', (req,res)=>{
const dataStream = got.stream({
url: "http://localhost:8000/products",
method: "GET",
hooks: {
beforeRequest: [
options => {
var token= 'Bearer ' + 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE2MTkzODA0NjIsImV4cCI6MTYxOTM4NDA2Mn0.JoJbRpPniGuMbwULEtts7I19QxEImvarT6AoqVuNb9w'
options.headers['Authorization'] = token;
}
]
}
});
pipeline(dataStream, res, (err) => {
if (err) {
console.log(err);
res.sendStatus(500);
}
});
});