const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
const axios = require("axios");
const app = express();
const PORT = 3001;
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const UPSTOX_CLIENT_ID = "ID"
const UPSTOX_CLIENT_SECRET = "c-secret";
const UPSTOX_REDIRECT_URI = "https://api.upstox.com";
const UPSTOX_API_VERSION = "v2";
mongoose
.connect(
"mongodb+srv://vsmarttrading97:<password>.mongodb.net/Node-APi?retryWrites=true&w=majority"
)
.then(() => {
console.log("Connected to MongoDB");
})
.catch((err) => {
console.log("Error connecting to MongoDB:", err);
});
// Upstox login endpoint
app.get("/upstox-login", async (req, res) => {
const authorizeUrl = "https://api.upstox.com/v2/login/authorization/dialog";
const queryParams = {
client_id: UPSTOX_CLIENT_ID,
redirect_uri: UPSTOX_REDIRECT_URI,
apiVersion: UPSTOX_API_VERSION,
state: "your_state", // Optional
scope: "your_scope", // Optional
};
const upstoxLoginUrl = `${authorizeUrl}?${new URLSearchParams(queryParams)}`;
res.json({ loginUrl: upstoxLoginUrl });
});
app.get("/upstox-callback", async (req, res) => {
const code = req.query.code;
console.log("Received authorization code:", code);
// Exchange code for access token
const tokenUrl = "https://api.upstox.com/v2/login/authorization/token";
const tokenParams = {
code: code,
client_id: UPSTOX_CLIENT_ID,
client_secret: UPSTOX_CLIENT_SECRET,
redirect_uri: UPSTOX_REDIRECT_URI,
grant_type: "authorization_code",
};
try {
const tokenResponse = await axios.post(tokenUrl, null, {
headers: {
"Api-Version": UPSTOX_API_VERSION,
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
},
params: tokenParams,
});
const userData = tokenResponse.data;
// Store user data in MongoDB
const newUser = new User(userData);
await newUser.save();
// Send a response back to the frontend
res.json(userData);
} catch (error) {
console.error("Error exchanging code for token:", error.message);
res.status(500).json({ error: "Internal Server Error" });
}
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
I believe this is the same discussion as mentioned previously.
yes its the same discussion as mentioned prev.
here i am sending backend, frontend code
above all backend code.
below frontend code.
i am following the given documents, why i am getting errors and rendering to Swagger UI.
please guide me