not able to hit the router in the browser when I hit the url - javascript

I have a working codebase where they have already setup node proxy and jwt.
my server is running at 1010 port
but when I hit this url http://localhost:1010/sampletest
I am getting an error in the browser screen Cannot GET /sampletest
even I hit this url http://localhost:1010/jump/api/v1 but still I am getting same error
can you tell me how to fix it or am I missing anthing in the configurations
providing my index.js and server.js code below
sports.js
const express = require('express');
const axios = require('axios');
const mime = require('mime-types');
const router = express.Router();
const ResponseUtil = require('../../utils/ResponseUtil');
const AppConstants = require('../../../constants/AppConstants');
const credentials = require('../../../internals/credentials.json');
const memberGroupingHelper = require('../../helpers/rank/memberGrouping');
const exportHelper = require('../../helpers/rank/rankExportHelper');
const formatExportData = require('../../helpers/rank/formatExportData');
const rankCommonHelper = require('../../helpers/rank/rankCommonHelper');
const rankProvDataHelper = require('../../helpers/group/getProvData');
//const aggregateHelper = require('../../helpers/group/aggregateFilter');
const { rankAggregatelastrsApi } = require('jump-svc-utils');
//router.get('/:searchMode/:lastrSearch', (req, res, next) => {
router.get('/sampletest', (req, res, next) => {
const { originalUrl } = req;
//console.log(" originalUrl ", originalUrl);
const mode = req.params.searchMode;
const value = encodeURIComponent(req.params.lastrSearch);
console.log("document 40--->", mode);
console.log("for document Testing0--->", mode);
const url = `/jkjkjk/sdjksdjkjksdjksd/sdklsdlksdklsdkl`;
axios.get(AppConstants.GET_JWT_TOKEN_URL, {
auth: {
username: credentials.auth.racfId, password: credentials.auth.password
}
})
.then((jwtResponse) => {
// var jwtToken = `Bearer ${jwtResponse.data.jwt}`;
var jwtToken = `Bearer 787878bjhbnmnmmwqdqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwqwqw`;
axios.get(url, { headers: { "Authorization": jwtToken } })
.then((response) => {
console.log("document then0--->", response);
const file = Buffer.from(response.data.content, 'base64');
const fileType = mime.contentType(response.data.contentInfo.fileType);
const fileExtension = response.data.contentInfo.fileType.toLowerCase();
const fileName = `filename=${response.data.contentInfo.id}.${fileExtension}`;
res.set('Content-Type', fileType);
res.set('Content-disposition', `attachment; ${fileName}`);
res.send(file);
})
.catch((e) => {
console.log("e catch document0--->", e);
console.log("e.message catch document0--->", e.message);
console.log("catch document--->", e.response);
if (e.response) {
return res.status(e.response.status).send(e.response.data);
}
res.status(500).send(e.message || 'Something wrong');
});
});
ResponseUtil.callService(res, url);
});
module.exports = router;
index.js
const express = require('express')
const app = express()
const port = 1010
const jumpServices = require('./services/jump');
const compression = require('compression');
var BodyParser = require('body-parser');
const glob = require('glob');
const path = require('path');
app.use('/jump/api/v1', jumpServices);
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({
extended: true
}));
//app.use(compress())
// app.use(compression());
// include all the controllers
const controllers = glob.sync(path.join(__dirname, '/controllers/**/*.js'));
console.log("controllers--->", controllers);
controllers.forEach((controllerFileName) => {
require(controllerFileName)(app); //eslint-disable-line
});
app.listen(port, (err) => {
if (err) {
return console.log('something bad happened', err)
}
console.log(`server is listening on ${port}`)
})

I don't see any calls registering your sub Routers with the top level express application. You should need to call app.use for each of your sub routers.

Related

I am trying to make routes but somehow express routers are not working

I think that I am not making any mistake in the code. I am not getting why this is not working when I am trying to access it on localhost. working fine on postman. should I change something in the browser setting
server.js (starting point- calling all the methods here)
const express = require('express')
const app = express();
const controller = require('./mailtemplate/mailtemplate.controller')
var http = require("http")
app.use('/mailtemplate', controller);
app.get('/', (req,res) => {
res.send("Server is Live")
})
var server = http.createServer(app);
server.listen("3000", "here is my IP address", () => {
console.log("Server is running")
});
controller.js - setting routs here
const express = require('express');
const router = express.Router();
const app = express();
const mailtemplateService = require('./mailtemplate.service');
router.post('/template', getMail);
app.use(router)
function getMail(req, res, next) {
mailtemplateService.getDataFromOpenAIAPI(req.body)
.then((response) => {
console.log(response);
res.json();
})
.catch(err => next(err))
}
module.exports = router;
service.js - logic of the fetching data from the api
const express = require('express')
const db = require('../_helpers/db');
const MailTemplate = db.MailTemplate;
async function getDataFromOpenAIAPI(prompt) {
const apiKey = "apikey";
const endpoint = "https://api.openai.com/v1/completions";
try{
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
model: "text-davinci-003",
prompt:prompt,
max_tokens : 600,
temperature:0.6
})
})
const data = await response.json();
console.log(data.choices[0].text);
return data;
}catch (error){
console.log(error);
}
}
module.exports = {getDataFromOpenAIAPI};

Express API returning HTML, not JSON, on GET request w/ JWT Token

I've been trying to wrap my head around this all day. I'm trying to figure out where this token is.... Any ideas?
All I keep getting is the following error and a return in text/html from my Express backend
SyntaxError: Unexpected token   in JSON at position 3
index.js
const express = require("express");
const app = express();
const cors = require("cors");
var bodyParser = require("body-parser");
const dotenv = require('dotenv');
const { default: mongoose } = require("mongoose");
const auth_routes = require('./routes/auth.routes');
const rate_routes = require('./routes/rate.routes');
dotenv.config();
const port = process.env.PORT || 5000;
const mongo_uri = 'mongodb://' + process.env.MONGO_USER + ':' + process.env.MONGO_PASSWD + '#localhost:27017/home?authSource=admin';
mongoose.connect(mongo_uri)
.then((resp) => {
console.log('Connected to MongoDB');
}).catch((err) => {
console.error('Error: ', err.reason)
});
app.use(bodyParser.json());
app.use(
bodyParser.urlencoded({
extended: false,
}),
);
app.use(cors());
app.listen(port, () => { console.log("Server is running on port 5000");});
...
...
app.get('/', (req, res) => {
res.send("Welcome to the Behemoth API platform")
});
app.set('userToken', userToken);
app.use('/v1/user', auth_routes);
app.use('/v1/rates', rate_routes);
rate.routes.js - the api call
const express = require('express');
const auth_middle = require('../middleware/auth');
const axios = require("axios");
const router = express.Router();
router.route('/').get(auth_middle, async function (req, res) {
try {
let userToken = req.app.get('userToken');
const reqBody = [ {
....
....
} ];
let rateResponse = await axios.post('https://xxxxxxxx', reqBody, {
headers: {
'Authorization': 'Bearer ' + userToken
}
});
var StockRate = rateResponse.data.StockData;
res.send(rateResponse.data);
} catch (e) {
console.log(e.stack);
res.status(500).send({error: e.message + " / " + e.keyword });
}
});
module.exports = router;
auth.js
const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');
dotenv.config();
module.exports = (req, res, next) => {
try {
console.log(req.headers.authorization);
const token = req.headers.authorization.split(" ")[1];
jwt.verify(token, process.env.JWT_SECRET_KEY);
next();
} catch (err) {
console.log(err);
res.send(401).json({ message: err })
}
}

how to fix Error with Nodejs and 'gridfs-stream'

I am trying to follow along a tutorial and use nodejs with 'gridfs-stream' along with a react front end. The tutorial is from last year in 2020.
Here is my code.
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors')
const multer = require('multer');
const {GridFsStorage} = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const path = require('path');
const Pusher = require('pusher')
const mongoPosts = require ('./mongoPosts.js')
// const currentTournamentControllers = require('../controllers/currenttournament-controllers');
const app = express();
const port = process.env.PORT || 9000
app.use(bodyParser.json())
app.use(cors())
const mongoURI = 'mongodb+srv://fbclient:rmbmbkvZVHw3e6OK#cluster0.emaw1.mongodb.net/myFirstDatabase?retryWrites=true&w=majority'
const conn = mongoose.createConnection(mongoURI);
mongoose.connect(mongoURI)
mongoose.connection.once('open', () => {
console.log('DB Connected')
})
let gfs
conn.once('open', () => {
// Init stream
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('images');
});
const storage = new GridFsStorage({
url: mongoURI,
file: (req, file) => {
return new Promise((resolve, reject) => {{
const filename = `image-${Date.now()}${path.extname(file.originalname)}`
const fileInfo = {
filename: filename,
bucketName: 'images'
}
resolve (fileInfo)
}})
}
})
const upload = multer({storage})
app.get('/', (req, res) => res.status(200).send('hello world'))
app.post('/upload/image', upload.single('file'), (req, res) => {
res.status(201).send(req.file)
})
app.post('/upload/post', (req, res) => {
const dbPost = req.body
console.log(dbPost)
mongoPosts.create(dbPost, (err, data) => {
if(err){
res.status(500).send(err)
} else {
res.status(201).send(data)
}
})
})
app.get('/retrieve/image/single', (req, res) => {
console.log(req.query.name)
gfs.files.findOne({filename: req.query.name}, (err, file) => {
if(err) {
res.status(500).send(err)
} else {
console.log(file)
if(!file || file.length === 0) {
console.log("hi i errored out")
res.status(404).json({err: 'file not found'})
} else {
console.log("hi i am trying to read")
const readstream = gfs.createReadStream(file.filename)
readstream.pipe(res)
}
}
})
})
app.get('/retrieve/posts', (req, res) => {
mongoPosts.find((err, data) => {
if(err){
res.status(500).send(err)
} else {
data.sort((b,a) => {
return a.timestamp - b.timestamp
})
res.status(200).send(data)
}
})
})
app.listen(port, () => console.log(`listening on localhost:${port}`))
The problem is with readstream. When I am trying to retrieve the data it shows the error
TypeError: grid.mongo.ObjectID is not a constructor
I did some debugging and figured out that this can be fixed by changing a value inside the gridfs.js file in the node_modules. The change being suggested on Stack Overflow was this :-
this._store = new grid.mongo.GridStore(grid.db, this.id || new grid.mongo.ObjectID(), this.name, this.mode, options);
changed to
this._store = new grid.mongo.GridStore(grid.db, this.id || new grid.mongo.ObjectId(), this.name, this.mode, options);
The suggestion was to change the grid.mongo.ObjectID value to grid.mongo.ObjectId. So I did that. Now the error coming out is as follows:-
TypeError: grid.mongo.GridStore is not a constructor
For this I am not getting any fixes on stack overflow or any other websites. Can someone please help

Axios throwing 404 error on POST request although express route exists

I am creating a sveltejs/sapper app. I am trying to post some info from the frontend to the backend express server using axios in the script tag. Although get requests from external sources are succeeding, axios is throwing a 404 error while posting to the express route. Refer these images posted below.
server.js
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
import sirv from 'sirv';
import * as sapper from '#sapper/server';
const app = express();
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';
app.use(
sirv('static', {dev}),
sapper.middleware(),
bodyParser.json(),
bodyParser.urlencoded({extended:true})
);
app.post('/task', (req, res) => {
res.sendStatus(200);
console.log(req.body);
// fs.writeFile(`./downloads/${req.body.file}`, req.body.buffer, (err) => {
// if (err) throw err;
// console.log(`${res.file} downloaded to backend server`);
// });
});
app.listen(PORT, err => {
if (err) console.log('error', err);
});
frontend script
<script>
//variables
let start = false;
let url = '';
let filename = '';
let downloadProgress = 0;
let error = false;
let progressBarStyle = 'bg-success';
//automated Events
$:downloadLabel = downloadProgress.toString();
$:if(downloadLabel == '100') {
progressBarStyle = 'bg-warning';
downloadLabel = 'DOWNLOAD COMPLETE! FILE WILL BE TRANSFERED SHORTLY!';
}
//axios config
let config = {
onDownloadProgress: progressEvent => {
downloadProgress = Math.floor((progressEvent.loaded * 100) / progressEvent.total); }
}
//functions
function startDownload() {
start = true;
axios.get(url, config).then((res) => {
if(res.status == 200) {
let data = {
file: filename,
buffer: res.data
}
axios.post('/task', data).then(() => {
console.log('Data sent to server');
}).catch((err) => {
console.log(err);
});
}
else {
error = true;
}
}).catch((err) => {
error = true;
});
}
function reset() {
// start = false;
// url = '';
// filename = '';
// downloadProgress = 0;
window.location.reload();
}
</script>
browser console
network tab
You use sapper,
Try to read docs.
example:
const express = require('express');
import sirv from 'sirv';
import compression from 'compression';
import * as sapper from '#sapper/server';
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === 'development';
const app = express();
app
/* add your handlers here */
.post('/task', (req, res, next) => {
res.sendStatus(200);
console.log(req.body);
})
.use(
compression({ threshold: 0 }),
sirv('static', { dev }),
sapper.middleware()
)
.listen(PORT, err => {
if (err) console.log('error', err);
});
I find here solution
You have to send something in the request handler:
(req, res) => {
res.sendStatus(200);
}

how to actually use the data requested using discord oauth2

I am not exactly sure how to go about using/accessing the data requested from a discord oauth2 authentication. I have requested to access the guilds the user is in and the username and avatar of the user. I get a successful authentication, but my question is how do i use and access that data? This is my code currently:
server.js
const express = require('express');
const path = require('path');
const app = express();
app.use('/static', express.static(path.join(__dirname, 'static')));
app.get('/', (req, res) => {
res.status(200).sendFile(path.join(__dirname, 'index.html'));
});
app.listen(50451, () => {
console.info('Running on port 50451');
});
app.use('/api/discord', require('./api/discord'));
app.use((err, req, res, next) => {
switch (err.message) {
case 'NoCodeProvided':
return res.status(400).send({
status: 'ERROR',
error: err.message,
});
default:
return res.status(500).send({
status: 'ERROR',
error: err.message,
});
}
});
discord.js
const express = require('express');
const dotenv = require('dotenv').config()
const fetch = require('node-fetch');
const btoa = require('btoa');
const { catchAsync } = require('../utils');
const router = express.Router();
const scopes = ['identify', 'guilds'];
const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
const redirect =
encodeURIComponent('http://localhost:50451/api/discord/callback');
router.get('/login', (req, res) => {
res.redirect(`https://discordapp.com/api/oauth2/authorize?client_id=${CLIENT_ID}&redirect_uri=${redirect}&response_type=code&scope=identify%20guilds`);
});
router.get('/callback', catchAsync(async (req, res) => {
if (!req.query.code) throw new Error('NoCodeProvided');
const code = req.query.code;
const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
const response = await fetch(`https://discordapp.com/api/oauth2/token?grant_type=authorization_code&code=${code}&redirect_uri=${redirect}`,
{
method: 'POST',
headers: {
Authorization: `Basic ${creds}`,
},
});
const json = await response.json();
res.redirect(`/success/?token=${json.access_token}`);
}));
module.exports = router;
Any help will be greatly appreciated. Thanks!
It's almost the same as the way you use the req.query.code to get the access_token.
const fetchDiscordUserInfo = await fetch('http://discordapp.com/api/users/#me', {
headers: {
Authorization: `Bearer ${json.access_token}`,
}
});
const userInfo = await fetchDiscordUserInfo.json();
yourUserId = `${userInfo.id}`;
yourUserName = `${userInfo.username}`;
// or simply...
console.log(userInfo);

Categories

Resources