Socket.io 404 Error - Client not connecting - javascript
When deploying a twitter streaming app which is working well on my local environment, to a live webserver, I'm getting a 404 error related to socket.io. I saw that there a numerous similar questions here already but did not find an answer solving the problem I'm facing.
Problem description:
Once I start server.js, it correctly logs 'Listening on Port 3000' to the console (terminal)
However, the message "Client connected..." is not triggered
In the browser console, I'm seeing the error message "GET https://exampledomain.com/socket.io/?EIO................(etc) - 404 - XHR failed loading"
I have already tried the following changes without success, amongst other things:
Changed the server.js code from const http = require('http') to const https = require('https')
Changed the port from 3000 to others to rule out a certain port # is already in use elsewhere, e.g. 8001 or 3333
The full server code (in public_html/server/server.js):
const http = require('http')
const path = require('path')
const express = require('express')
const socketIo = require('socket.io')
const needle = require('needle')
const config = require('dotenv').config()
const TWITTER_BEARER_TOKEN = 'xxxxxx'
const PORT = process.env.PORT || 3000
const app = express()
const server = http.createServer(app)
const io = socketIo(server)
console.log(path.resolve(__dirname, '../', 'public_html/client', 'index.html'))
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, '../', 'public_html/client', 'index.html'))
// /usr/www/users/antick/public_html/client/index.html
})
const rulesURL = 'https://api.twitter.com/2/tweets/search/stream/rules'
const streamURL = 'https://api.twitter.com/2/tweets/search/stream?tweet.fields=public_metrics&expansions=author_id,attachments.media_keys&media.fields=duration_ms,height,media_key,preview_image_url,public_metrics,type,url,width&user.fields=profile_image_url'
const rules = [{ value: 'corruption' }]
// Get stream rules
async function getRules() {
const response = await needle('get', rulesURL, {
headers: {
Authorization: `Bearer ${TWITTER_BEARER_TOKEN}`
}
})
return response.body
}
// Set stream rules
async function setRules() {
const data = {
add: rules
}
const response = await needle('post', rulesURL, data, {
headers: {
'content-type': 'application/json',
Authorization: `Bearer ${TWITTER_BEARER_TOKEN}`
}
})
return response.body
}
// Delete stream rules
async function deleteRules(rules) {
if (!Array.isArray(rules.data)) {
return null
}
const ids = rules.data.map((rule) => rule.id)
const data = {
delete: {
ids: ids
}
}
const response = await needle('post', rulesURL, data, {
headers: {
'content-type': 'application/json',
Authorization: `Bearer ${TWITTER_BEARER_TOKEN}`
}
})
return response.body
}
function streamTweets(socket) {
const stream = needle.get(streamURL, {
headers: {
Authorization: `Bearer ${TWITTER_BEARER_TOKEN}`
}
})
stream.on('data', (data) => {
try {
const json = JSON.parse(data)
console.log(json)
socket.emit('tweet', json)
} catch (error) {}
})
}
io.on('connection', async () => {
console.log('Client connected...')
let currentRules
try {
// Get all stream rules
currentRules = await getRules()
// Delete all stream rules
await deleteRules(currentRules)
// Set rules based on array above (Rules)
await setRules()
} catch (error) {
console.error(error)
process.exit(1)
}
streamTweets(io)
})
server.listen(PORT, () => console.log(`Listening on Port ${PORT}`))
My client code - excerpt only (in public_html/client/index.html):
<div class="container">
<div id="tweetStream"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.1.2/socket.io.js" integrity="sha512-iZIBSs+gDyTH0ZhUem9eQ1t4DcEn2B9lHxfRMeGQhyNdSUz+rb+5A3ummX6DQTOIs1XK0gOteOg/LPtSo9VJ+w==" crossorigin="anonymous" referrerpolicy="no-referrer">
</script>
<script>
const tweetStream = document.getElementById('tweetStream')
const socket = io()
//const socket = io.connect('https://www.exampledomain.com:3000/');
const tweets = []
socket.on('connect', () => {
console.log('Connected to server...')
})
socket.on('tweet', (tweet) => {
// (code continues here)
My suspicion is that is has to do something with the paths used in these two locations:
in server/server.js:
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, '../', 'public_html/client', 'index.html'))
// resolves to: /usr/www/users/antick/public_html/client/index.html
})
in client/index.html: const socket = io() //
What else could possibly cause the error described above? I am grateful for any help. Thanks!
With help from a pro developer I was finally able to fix the problem so I would like to post the solution.
The two main points were:
Open Port # 3000 to any IPs (as it is unknown from which IP address a client would access the site)
Install pm2 in addition to node in order to constantly stream the tweets
The full resulting code looks as follows:
A) Server (index.js):
const http = require('http')
const path = require('path')
const express = require('express')
const socketIo = require('socket.io')
const needle = require('needle')
const config = require('dotenv').config()
const TOKEN = process.env.TWITTER_BEARER_TOKEN
const PORT = process.env.PORT || 3000
const app = express()
const server = http.createServer(app)
const io = socketIo(server)
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, '../', 'client', 'index.html'))
})
const rulesURL = 'https://api.twitter.com/2/tweets/search/stream/rules'
const streamURL = 'https://api.twitter.com/2/tweets/search/stream?tweet.fields=public_metrics&expansions=author_id,attachments.media_keys&media.fields=duration_ms,height,media_key,preview_image_url,public_metrics,type,url,width&user.fields=profile_image_url'
const rules = [{ value: 'searchterm' }]
// Get stream rules
async function getRules() {
const response = await needle('get', rulesURL, {
headers: {
Authorization: `Bearer ${TOKEN}`
}
})
return response.body
}
// Set stream rules
async function setRules() {
const data = {
add: rules
}
const response = await needle('post', rulesURL, data, {
headers: {
'content-type': 'application/json',
Authorization: `Bearer ${TOKEN}`
}
})
return response.body
}
// Delete stream rules
async function deleteRules(rules) {
if(!Array.isArray(rules.data)) {
return null
}
const ids = rules.data.map((rule) => rule.id)
const data = {
delete: {
ids: ids
}
}
const response = await needle('post', rulesURL, data, {
headers: {
'content-type': 'application/json',
Authorization: `Bearer ${TOKEN}`
}
})
return response.body
}
function streamTweets (socket) {
const stream = needle.get(streamURL, {
headers: {
Authorization: `Bearer ${TOKEN}`
}
})
stream.on('data', (data) => {
try {
const json = JSON.parse(data)
console.log(json)
console.log(json.includes.media[0])
socket.emit('tweet', json)
} catch (error) {}
})
}
io.on('connection', async () => {
console.log('Client connected...')
let currentRules
try {
// Get all stream rules
currentRules = await getRules()
// Delete all stream rules
await deleteRules(currentRules)
// Set rules based on array above (Rules)
await setRules()
} catch (error) {
console.error(error)
process.exit(1)
}
streamTweets(io)
})
server.listen(PORT, () => console.log(`Listening on Port ${PORT}`))
B) Client (index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1"
crossorigin="anonymous"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css"
integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA=="
crossorigin="anonymous"
/>
<title>Real-Time Tweet Stream</title>
</head>
<body>
<nav class="navbar navbar-dark bg-dark">
<div class="container">
Real-Time Tweet Stream
</div>
</nav>
<div class="container">
<div id="tweetStream"></div>
</div>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.4/socket.io.js"
integrity="sha512-aMGMvNYu8Ue4G+fHa359jcPb1u+ytAF+P2SCb+PxrjCdO3n3ZTxJ30zuH39rimUggmTwmh2u7wvQsDTHESnmfQ=="
crossorigin="anonymous"
></script>
<script>
const tweetStream = document.getElementById('tweetStream')
const socket = io('IP.IP.IP.IP:3000' , { transports : ['websocket'] } ) // webserver IP address
const tweets = []
socket.on('connect', () => {
console.log('Connected to server...')
})
socket.on('tweet', (tweet) => {
// console.log(tweet)
const tweetData = {
id: tweet.data.id,
text: tweet.data.text,
username: `#${tweet.includes.users[0].username}`,
}
const tweetEl = document.createElement('div')
tweetEl.className = 'card my-4'
tweetEl.innerHTML = `
<div class="card-body">
<h5 class="card-title">${tweetData.text}</h5>
<h6 class="card-subtitle mb-2 text-muted">${tweetData.username}</h6>
<a class="btn btn-primary mt-3" href="https://twitter.com/${tweetData.username}/status/${tweetData.id}">
<i class="fab fa-twitter"></i> Go To Tweet
</a>
</div>
`
tweetStream.appendChild(tweetEl)
})
</script>
</body>
</html>
Related
CORS errors after deployment to render, worked fine locally
like the title says, here is my server file, I have tried every solution I could find on google yet I am still getting CORS errors. specifically XHROPTIONShttps://slug-panel-api.onrender.com/login server.js: const express = require('express'); const cors = require('cors'); const bodyParser = require('body-parser') const mongoose = require('mongoose') const userSchema = require('../../SlugAPI/Schemas/SlugSchemas') const divisionSchema = require('../src/SlugSchemas/DivisionSchemas/DivisionSchema') const subDivisionSchema = require('../src/SlugSchemas/DivisionSchemas/SubDivisionSchema') const teamSchema = require('../src/SlugSchemas/DivisionSchemas/TeamSchema') const divisionMemberSchema = require('../src/SlugSchemas/DivisionSchemas/DivisionMemberSchema') let CryptoJS = require('crypto-js') const PORT = process.env.PORT || 8080; const app = express(); app.use(cors({ origin: "https://slug-panel.onrender.com", headers: { "Access-Control-Allow-Origin": "https://slug-panel.onrender.com", "Access-Control-Allow-Credentials": true }, })); mongoose.set("debug") const usar_db = mongoose.createConnection("mongodb:/<username>:<password>#slug-db:27017/usarAdmin?authSource=admin"); const User = usar_db.model('User', userSchema) const Division = usar_db.model('Division', divisionSchema) const SubDivision = usar_db.model('SubDivision', subDivisionSchema) const Team = usar_db.model('Team', teamSchema) const DivisionMember = usar_db.model('Division_Member', divisionMemberSchema) function generateUserRegistrationKey(username, discord_id, rank, authentication_level) { let key = username + '/' + discord_id.toString() + '/' + rank + '/' + authentication_level const ciphertext = CryptoJS.AES.encrypt(key, 'secret').toString() return ciphertext } function decryptUserRegistrationKey(key) { const bytes = CryptoJS.AES.decrypt(key, 'secret') const originalText = bytes.toString(CryptoJS.enc.Utf8) return originalText } app.post('/login', bodyParser.json(), async (req, res, next) => { const user = req.body.username let pw = req.body.password pw = CryptoJS.SHA256(pw) let exists = await User.findOne({username: user}) if (exists) { if (pw.toString() === exists['password']) { res.send({ token: 'test123' }) } else { res.send({ error: 'passwordNotFound' }) } } else { res.send({ error: 'userNotFound' }) } }); app.post('/generate', bodyParser.json(), async function (req, res, next) { let username = req.body.username let discord_id = req.body.discord_id let rank = req.body.rank let authentication_level = req.body.authentication_level let exists = await User.exists({discord_id: discord_id}) let regKey = generateUserRegistrationKey(username, discord_id, rank, authentication_level) const newUser = User({ username: username, discord_id: discord_id, rank: rank, regKey: regKey, authentication_level: authentication_level, }) if (!exists) { newUser.save() .then(r => console.log("User " + username + " added to db")) res.send({regKey: regKey}) } }) app.post('/register', bodyParser.json(), async function (req, res, next) { let key = req.body.regKey let pw = CryptoJS.SHA256(req.body.password).toString() let decryptedKey = decryptUserRegistrationKey(key).split('/') let exists = await User.find({regKey: key}, function(err, docs) { if (err) { console.log(err) } else { console.log('Result: ', docs) console.log(pw) } }).clone() if (!exists) { res.send({user: null}) } else { res.send(JSON.stringify(exists)) } await User.findOneAndUpdate({regKey: key}, { is_registered: true, password: pw, authentication_level: decryptedKey[decryptedKey.length - 1]}) }) app.post('/createDivision', bodyParser.json(), async function (req, res, next) { let div_name = req.body.division_name let div_id = req.body.division_id let exists = await Division.findOne({division_name: div_name}, function (err, docs) { if (err) { console.log(err) } else { console.log(docs) } }).clone() let idexists = await Division.findOne({division_id: div_id}, function (err, docs) { if (err) { console.log(err) } else { console.log(docs) } }).clone() if (!exists || !idexists) { const newDivision = new Division({ division_name: div_name, division_id: div_id }) newDivision.save() .then(() => console.log('Division ' + div_name + ' has been added to the db')) res.send(JSON.stringify(newDivision)) } else { res.send({errorcode: 420}) } }) app.post('/createSubDivision/:divid', bodyParser.json(), async function (req, res, next) { const division = req.params['divid'] const sub_name = req.body.subdivision_name const sub_id = req.body.subdivision_id let exists = await Division.findOne({division_id: division}, function (err, docs) { if (err) { console.log(err) } else { console.log(docs) } }).clone() if (exists) { let subdivid_exists = await Division.findOne({ division_id: division, subdivisions: { $elemMatch: {subdivision_id: sub_id} } }) let subdiv_exists = await Division.findOne({ division_id: division, subdivisions: { $elemMatch: {subdivision_name: sub_name} } }) if (!subdivid_exists || !subdiv_exists) { const subDiv = new SubDivision({ subdivision_name: sub_name, subdivision_id: sub_id, }) await Division.findOneAndUpdate({division_id: division}, { $push: {subdivisions: subDiv}}) console.log('subdivision ' + sub_name + ' added to: ' + exists.division_name) res.send(JSON.stringify(subDiv)) } else { res.send({division:'exists'}) } } }) app.listen(PORT, () => console.log('API is running on ' + PORT)); Tried every solution I could find both on random google websites and on stackoverflow. as stated previously it worked fine on the development server hosted locally. for reference, here is how I am using fetch throughout the frontend async function loginUser(credentials) { return fetch('https://slugga-api.onrender.com/login', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': 'true' }, body: JSON.stringify(credentials) }) .then(data => data.json()) } Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://slugga-api.onrender.com/login. (Reason: CORS request did not succeed). Status code: (null). Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://slugga-api.onrender.com/login. (Reason: CORS request did not succeed). Status code: (null). Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource. asyncToGenerator.js:6:4 Babel 6 c Login.js:20 React 11 bind_applyFunctionN self-hosted:1683 Wt self-hosted:1640 React 3 forEach self-hosted:4909 React 2 <anonymous> index.js:7 <anonymous> index.js:17 <anonymous> index.js:17
You're misusing those CORS headers, both on the client side and on the server side. You should familiarise better with CORS and with the API of Express.js's CORS middleware. Client side The Access-Control-Allow-Origin header is a response header; including it in a request makes no sense. async function loginUser(credentials) { return fetch('https://slugga-api.onrender.com/login', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': 'true' // incorrect }, body: JSON.stringify(credentials) }) .then(data => data.json()) } Server side The headers property of your CORS config corresponds to request headers that you wish to allow, but what you've listed are response headers. app.use(cors({ origin: "https://slug-panel.onrender.com", headers: { "Access-Control-Allow-Origin": "https://slug-panel.onrender.com", // incorrect "Access-Control-Allow-Credentials": true // incorrect }, })); Instead, you most likely want something like app.use(cors({ origin: "https://slug-panel.onrender.com", headers: ["Content-Type"], credentials: true, }));
Fixed the issue by changing the CORS initialization in server.js const app = express(); app.use(cors({ origin: "https://slug-panel.onrender.com" } )) app.options('*', cors())
Data not Found as POST request returns `JSON.stringify(value); TypeError: Converting circular structure to JSON`
I have two functions in functions.js - postData and startProcess. I am calling both functions in a function in server.js called sendData. sendData is then called in the app.post route. In sendData, getData is called first and returns an id. This id is passed to startProcess and after it is run, a message that says 'success` should be printed. If it fails, a message that says 'failed to complete process should be returned'. It seems like postData runs successfully, but startProcess is unable to pick or use its response as id. When I run just the postData function in SendData, I get this error message: JSON.stringify(value); TypeError: Converting circular structure to JSON What am I missing and how can I properly implement this? functions.js const axios = require("axios"); const BASE_URL = "http://localhost:1770"; const startProcess = async (id) => { const headers = { "Content-type": "application/json", }; try { return axios.post(`${BASE_URL}/start/${id}`, { headers }); } catch (error) { console.error(error); } }; const postData = async (body) => { const headers = { "Content-type": "application/json", }; try { return axios.post(`${BASE_URL}/data`, body, { headers }); } catch (error) { console.error(error); } }; server.js const express = require("express"); const process = require("./functions.js"); const payload = require("./payload.json"); const res = require("express/lib/response"); // Create Express Server const app = express(); app.use(cors()); // Configuration-api const PORT = 5203; app.use(express.json()); const sendData = async (req, res, next) => { const body = payload; try { const response = await process.postData(body); if ((response.status = 200)) { let id = response.data; const processResult = await process.startProcess(id); if ((processResult.status = 200)) { res.send("successfully started process"); } } } catch (error) { console.error(error); } }; app.post("/data", sendData); app.listen(PORT, () => { console.log(`Running this application on the PORT ${PORT}`); });
Twilio - can't process phone number after clicking submit
I'm following this link for the tutorial (via twilio.) and have followed all the required steps but when I run the localhost and input a number, I get no text message, nor does the window for verification open. It just stays at the same page of "enter your phone number". Here's my HTML code <!DOCTYPE HTML> <HTML> <head> <title>Verify SMS Demo</title> <style> #verify-form, #response-text { display: none; } </style> </head> <body> <form id="phone-form"> <h2>Enter your phone number with country code:</h2> <input type="tel" id="phone-number-input" placeholder="15551235555" /> <input id="phone-submit" type="submit" /> </form> <form id="verify-form"> <h2>Enter your verification code:</h2> <input type="number" id="otp-input" placeholder="e.g. 123456" /> <input id="verify-submit" type="submit" /> </form> <div id="response-text"></div> </body> <script type="text/javascript" src = "script.js"></script> </html>` And here's my code for script.js: const phoneForm = document.getElementById('phone-form'); const verifyForm = document.getElementById('verify-form'); const responseText = document.getElementById('response-text'); let phoneNumber; phoneForm.addEventListener('submit', async e => { e.preventDefault(); phoneNumber = document.getElementById('phone-number-input').value; const response = await fetch('/send-notification', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({phoneNumber : phoneNumber }) }).catch(e => console.log(e)); if (response.ok) { phoneForm.style.display = 'none'; verifyForm.style.display = 'block'; } }); verifyForm.addEventListener('submit', async e => { e.preventDefault(); const otp = document.getElementById('otp-input').value; const data = { phoneNumber: phoneNumber, otp: top }; const response = await fetch('/verify-otp', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify(data) }).catch(e => console.log(e)); const check = await response.json(); const text = response.ok ? check.status : response.statusText; responseText.innerHTML = text; verifyForm.style.display = 'none'; responseText.style.display = 'block'; }); EDIT Here is my index.js file: const express = require('express'); const path = require('path'); require('dotenv').config(); const client = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN); const app = express(); const port = process.env.PORT || 3000; app.use(express.static(__dirname + '/public')); app.use(express.urlencoded({extended: true})); app.use(express.json()); app.get('/', (req, res) => { res.sendFile(path.join(__dirname, '/views/index.html')); }); app.post('/send-verification', async (req, res) => { client.verify.services(verify) .verifications .create({to: `+${req.body.phoneNumber}`, channel: 'sms'}) .then(verification => console.log(verification.status)) .catch(e => { console.log(e) res.status(500).send(e); }); res.sendStatus(200); }); app.post('/verify-otp', async (req, res) => { const check = await client.verify.services(verify) .verificationChecks .create({to: `+${req.body.phoneNumber}`, code: req.body.otp}) .catch(e => { console.log(e) res.status(500).send(e); }); res.status(200).send(check); }); app.listen(port); console.log('Server started at http://localhost:' + port);
Your front-end is making a request to /send-notification but your application end point is at /send-verification. Update your front-end code to: const response = await fetch('/send-verification', { and you should be good to go. Edit Now, in the server you are getting the error: sh-3.2$ node index.js Server started at localhost:3000 /Users/username/Downloads/keep_out-3/verify-sms-express/index.js:17 client.verify.services(verify) ^ ReferenceError: verify is not defined You have the line: const check = await client.verify.services(verify) In the blog post this is: client.verify.services(process.env.VERIFY_SERVICE_SID); So, you have replaced the verify service sid with a non-existant verify variable. Go back and make sure you have VERIFY_SERVICE_SID set in your .env file and then change the code back to the original, and then you should be good to go!
give role to OAuth2 authorised accounts on Discord
I am creating OAuth2 for my application by which the people who are redirected to the server by clickking it will get the verified role. Can somebody please help me on how i can add it in my script. Right now I am using the script given below: const express = require('express'); const { port } = require('./config.json'); const app = express(); app.get('/', (request, response) => { console.log(`The access code is: ${request.query.code}`) ; return response.sendFile('index.html', { root: '.' }); }); app.listen(port, () => console.log(`App listening at http://localhost:${port}`)); and from the index file they get redirected to the server here's the index.html script: <script> window.location.href = "https://discord.gg/DhsYQ3u4jj"; </script> <div id="info">Congrats! You have been successfully connected to Discord.</div> <a id="login" style="display: none;" href="https://discord.gg/jkBJarBY">Click here to Join Akudo's official Discord!</a> <script> window.onload = () => { const fragment = new URLSearchParams(window.location.hash.slice(1)); const [accessToken, tokenType] = [fragment.get('access_token'), fragment.get('token_type')]; if (!accessToken) { return (document.getElementById('login').style.display = 'block'); } fetch('https://discord.com/api/users/#me', { headers: { authorization: `${tokenType} ${accessToken}`, }, }) .then(result => result.json()) .then(response => { const { username, discriminator } = response; document.getElementById('info').innerText += ` ${username}#${discriminator}`; }) .catch(console.error); }; </script>
Passing token to another request in Node.js
In first request I'm asking external server to provide a token. And I'm getting it. Then I would like to use it in another request. All is done in express.js. What is the best solution to provide it to the another request? It looks like this: const express = require('express'); const axios = require('axios'); const config = require('./config'); const app = express(); axios.post('URL1', { email: config.email, password: config.password, }) .then(function(response) { console.log(response.data.token); //here I' getting the token }) .catch(function(error) { console.log(error); }); const headers = { headers: { 'Authorization': 'Token ' + token } }; //here I would like to use (for the use of a second request) axios.get('URL2', headers) .then(function(response) { console.log(response); }) .catch(function(error) { console.log(error); }); const PORT = process.env.PORT || 5000; app.listen(PORT); Of course I cannot just assign it to the variable. Thank you for helping!
You can call it in another function just as shown below. const express = require('express'); const axios = require('axios'); const config = require('./config'); const app = express(); axios.post('URL1', { email: config.email, password: config.password, }).then((response) => { // calling function here return handleToken(response.data.token); console.log(response.data.token); //here I' getting the token }).catch((error) => { console.log(error); }); //second request will be handled here const handleToken = (token) => { const headers = { headers: { 'Authorization': 'Token ' + token } }; //here I would like to use (for the use of a second request) axios.get('URL2', headers) .then((response) => { console.log(response); }).catch((error) => { console.log(error); }); } const PORT = process.env.PORT || 5000; app.listen(PORT); It's preferable if you write a separate function to avoid callback hell. EDIT - ROUTE WITH ASYNC/AWAIT app.get('/', async (req, res)=>{ try { let result = await axios.post('URL1', { email: config.email, password: config.password }); let final = await handleToken(response.data.token); // other operations here console.log(result); } catch (err) { //handle error here console.error(err); } }) //second request will be handled here const handleToken = async (token) => { try { const headers = { headers: { 'Authorization': 'Token ' + token } }; let response = await axios.get('URL2', headers); return response; } catch (err) { throw err; } }