i am getting a error of 401 & 500 after multiple way to access token.
here i am writing code.
app.post("/get-token", async (req, res) => {
const { code } = req.body;
if (!code) {
return res.status(400).json({ error: "Code is required" });
}
try {
const tokenResponse = await exchangeCodeForToken(code);
const accessToken = tokenResponse.access_token;
console.log("Access Token:", accessToken);
res.json({
email: tokenResponse.email,
exchanges: tokenResponse.exchanges,
products: tokenResponse.products,
broker: tokenResponse.broker,
user_id: tokenResponse.user_id,
user_name: tokenResponse.user_name,
order_types: tokenResponse.order_types,
user_type: tokenResponse.user_type,
poa: tokenResponse.poa,
is_active: tokenResponse.is_active,
access_token: accessToken,
extended_token: tokenResponse.extended_token,
});
} catch (error) {
console.error("Error exchanging code for token:", error.message);
console.error(
"Error details:",
error.response ? error.response.data : error.request
);
res.status(500).json({ error: "Internal Server Error" });
}
});
app.get("/get-token)
above file
async function exchangeCodeForToken(code) {
const tokenUrl = “https://api.upstox.com/v2/login/authorization/token”;
const headers = {
“Api-Version”: UPSTOX_API_VERSION,
“Content-Type”: “application/x-www-form-urlencoded”,
accept: “application/json”,
};
const data = new URLSearchParams();
data.append(“code”, code);
data.append(“client_id”, UPSTOX_CLIENT_ID);
data.append(“client_secret”, UPSTOX_CLIENT_SECRET);
data.append(“redirect_uri”, UPSTOX_REDIRECT_URI);
data.append(“grant_type”, “authorization_code”);
data.append(“upstox_code”, UPSTOX_API_CODE);
try {
const response = await axios.post(tokenUrl, data, { headers });
return response.data;
} catch (error) {
throw new Error(Failed to exchange code for token: ${error.message}
);
}
}
const authorizationCode = “q3w0Z4”;
const endpointUrl = “http://127.0.0.1:3001/get-token”;
const requestData = {
code: authorizationCode,
};
axios
.post(endpointUrl, requestData, {
headers: {
“Content-Type”: “application/json”,
},
})
.then((response) => {
console.log(“Access Token Response:”, response.data);
})
.catch((error) => {
console.error(“Error exchanging code for token:”, error.message);
});
please look at this is @Pradeep_Jaiswar @shanmu @Hariom_Gohel