import React, { useState, useEffect } from "react";
const App = () => {
const [authCode, setAuthCode] = useState("");
const handleAuth = () => {
const clientId = "";
const redirectUri = "http://127.0.0.1:3000";
const authUrl = `https://api.upstox.com/v2/login/authorization/dialog?response_type=code&client_id=${clientId}&redirect_uri=${redirectUri}`;
window.location.href = authUrl;
};
useEffect(() => {
const params = new URLSearchParams(window.location.search);
const code = params.get("code");
if (code) {
setAuthCode(code);
}
}, []);
useEffect(() => {
if (authCode) {
fetch("http://127.0.0.1:3001/api/token", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: `code=${authCode}&grant_type=authorization_code`,
})
.then((response) => response.json())
.then((data) => {
console.log(data);
const token = data.access_token;
console.log("Extracted access token:", token);
// Save token to localStorage
localStorage.setItem("accessToken", token);
})
.catch((error) => console.error("error at access-token", error));
}
}, [authCode]);
return (
<div className="container-fluid m-0 p-0">
<h1 className="text-success fs-1 text-center mt-1">
Invest in knowledge before investing in stocks{" "}
<span>
<p
className="text-end pe-4 "
style={{
fontSize: "9px",
fontWeight: "200",
}}
>
Data
</p>
</span>
</h1>
<div className="d-flex justify-content-center pt-4">
<button className="btn btn-outline-info" onClick={handleAuth}>
Authenticate
</button>
</div>
</div>
);
};
export default App;
above is frontend code
below is backend code
const express = require("express");
const axios = require("axios");
const dotenv = require("dotenv");
const cors = require("cors");
const bodyParser = require("body-parser");
dotenv.config();
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const port = 3001;
let accessToken = null;
// Route to handle login and store the access token
app.post("/api/token", async (req, res) => {
const { code } = req.body;
try {
const response = await axios.post(
"https://api.upstox.com/v2/login/authorization/token",
null,
{
params: {
code,
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
redirect_uri: process.env.REDIRECT_URI,
grant_type: "authorization_code",
},
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
},
}
);
accessToken = response.data.access_token; // Store access token
console.log("Access token stored:", accessToken);
res.json({ access_token: accessToken });
} catch (error) {
console.error(
"Error getting access token:",
error.response ? error.response.data : error.message
);
res.status(500).send("Error getting access token");
}
});
// Start server
app.listen(port, () => { console.log(`Server running at http://127.0.0.1:${port}`);
});
why i am not able to generate access token ??