I need to answer the client when they ask for a hash from the server which is used to generate and authorize for access to files, how can I confirm that the hash is equal to the message, using node.js and express:
const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const sha1 = require('sha1');
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.get('/', function(request, response) {
var x1 = request.query.x1;
var x2 = request.query.x2;
var x3 = request.query.x3;
var x4 = 654321;
var hash = sha1(x2+x3+x4)
});
app.listen(process.env.PORT || 3000, function() {
console.log("Server is running in port 3000!");
});
You can use the crypto module to generate and decode the hash. Here is an example.
const resizedIV = Buffer.allocUnsafe(16)
app.get('/', function(request, response) {
const key = crypto
.createHash("sha256")
.update('secret-key')//this should be a secret key
.digest()
const cipher = crypto.createCipheriv("aes256", key, resizedIV)
for (var prop in req.query) {
if (req.query.hasOwnProperty(prop)) {
cipher.update(req.query[prop], "binary", "hex")
}
}
const hash = cipher.final("hex")
res.send(hash)
});
and then you can decode it like this
app.get('/decode', function(req, res) {
const key = crypto
.createHash("sha256")
.update('secret-key')
.digest()
const decipher = crypto.createDecipheriv("aes256", key, resizedIV),
decipher.update(req.query.hash, "hex", "binary")
const decoded = decipher.final("binary")
res.send(decoded)
})
Related
I am working on a esp32 wifi speaker, I got the board going, and now I need to make a server from where you can stream what songs you'd like. I'm new to working on the backend and i'm having trouble with this error: node:internal/errors:465 ErrorCaptureStackTrace(err);
Here is my code:
const fs = require("fs");
const ytdl = require("ytdl-core");
const express = require("express");
var cors = require("cors");
var path = require("path");
const app = express();
var http = require("http").createServer(app);
const io = require("socket.io")(http);
const bodyParser = require('body-parser');
const port = process.env.PORT || 8080;
const adress = '127.0.0.1';
var clientGlob = null;
var destDir = "./Music";
var songs = [];
var songDur = [];
var playing = false;
var curSong = '';
app.use(express.json()); // to support JSON-encoded bodies
app.use(express.urlencoded({ extended: true })); // to support URL-encoded bodies
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname,"index.html"));
});
app.post("/downAudio", (req, res) => {
getAudio(req.body.url, res);
});
getAudio = (videoURL, res) => {
console.log(videoURL);
var stream = ytdl(videoURL, {
quality: "highestaudio",
filter: "audioonly",
})
var videoReadableStream = ytdl(videoURL, { filter: 'audioonly'});
ytdl.getInfo(videoURL).then((info) => {
console.log("title:", info.videoDetails.title);
console.log("rating:", info.player_response.videoDetails.averageRating);
console.log("uploaded by:", info.videoDetails.author.name);
var videoName = info.videoDetails.title.replace('|','').toString('ascii');
var videoWritableStream = fs.createWriteStream(destDir + '\\' + videoName + '.mp3');
var stream = videoReadableStream.pipe(videoWritableStream);
stream.on('finish', function() {
res.writeHead(204);
res.end();
});
console.log("File downloaded and added to the queue");
songs.push(destDir + '\\' + videoName + '.mp3');
var duration = parseInt(info.videoDetails.lengthSeconds);
songDur.push(duration*1000);
console.log("Audio added to the queue")
if(!playing)
play();
});
};
play = ()=>{
playing=true;
curSong=songs[0];
setTimeout(playNext(),songDur[0]);
}
playNext = ()=>
{
fs.unlink(curSong, function (err) {
if (err) throw err;
console.log('File deleted!');
});
songs.pop()
songDur.pop();
if(songs.length!=0)
play();
else
playing=false;
}
io.on("connection", (client) => {
clientGlob = client;
console.log("User connected");
});
app.listen(port,adress, () => {
console.log(`Server started, link: ${adress}:${port}`);
});
It downloads the songs fine but it has a problem in the playnext function. I cant relate this error to anything in there. What am I doing wrong?
Also any help into improving the code and performance is welcome.
If needed I will provide more information, thanks!
Fixed the problem, for some reason it didn't like the type of function I used. After making it a normal function playnext(){}... it worked.
I have a simple backend that I'd like to return a string of data whenever a POST request is made. The string is converted to JSON, but when I see that the response was successfully received by the client (the browser), the string is missing from the response data in the browser's console.
server.js (the request handler itself is simple, there's just a few dependencies listed)
const path = require('path');
const express = require('express');
const bp = require("body-parser");
const request = require("request");
const {createCanvas, loadImage} = require("canvas");
const cors = require('cors');
const requestIp = require('request-ip');
const { json } = require('body-parser');
const bodyParser = require('body-parser');
const wgServer = express();
const port = 3000;
const fs = require("fs");
const { createContext } = require("vm");
wgServer.use(cors())
wgServer.use(bp.json())
wgServer.use(bp.urlencoded({ extended: true }))
wgServer.use("/public", express.static(path.join(__dirname, 'public')));
wgServer.use(bodyParser.json({limit: '50mb'}))
wgServer.listen(port, function() {
console.log(`Weatherglyph server succesfully listening on port ${port}.`)
});
wgServer.post('/', async function (req, res) {
res.set('Content-Type', 'application/json');
... Lots of functions etc irrelevant to the question
let picpath = __dirname + "\\image.png";
let picbuff = fs.readFileSync(picpath);
let picbase64 = picbuff.toString('base64');
console.log(picbase64);
res.status(201).json({picbase64});
res.send();
})})
script.js
async function submitCity(){
let x = document.getElementById("wg_input").value;
console.log("Successfully captured city name:", x);
let toWeather = JSON.stringify({city: x});
console.log("Input data successfully converted to JSON string:", toWeather);
const options = {
method: 'POST',
mode: 'cors',
headers: {'Content-Type': 'application/json'},
body: toWeather
}
fetch('http://localhost:3000', options)
.then(res => console.log(res))
.catch(error => console.log(error))
}
Is the data (a .png converted to base64 and sent to the frontend) actually reaching the client and I just can't see it in Chrome's console, or am I sending it incorrectly?
This is my index.js file and i think i have placed the routes after installing bodyParser but still getting the syntax error.
const express = require('express'); //Framework to build server side application
const morgan = require('morgan'); //Logging the nodejs requests
const bodyParser = require('body-parser'); //To get the JSON data
const urls = require('./db/urls');
const app = express();
app.use(morgan('tiny'));
app.use(bodyParser.json());
app.use(express.static('./public')); //If a request comes with '/' check if file is in there if it is then serve it up.
// app.get('/', (req, res) => {
// res.send('Hello, World !!');
// });
app.post('/api/shorty', async (req, res) => {
console.log(req.body);
try {
const url = await urls.create(req.body); //Passing the body data which is JSON to create function
res.json(url);
} catch (error) {
res.status(500);
res.json(error)
}
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`listening on port ${port}`);
});
This is the urls.js file,I am not getting where have i messed up to make Syntax.JSON error in this file.
const db = require('./connection');
const Joi = require('joi');//Schema validation
const urls = db.get('urls');
const schema = Joi.object().keys({
name : Joi.string().token().min(1).max(100).required(),
url : Joi.string().uri({
scheme: [
/https?/ //get http 's' is optional
]
}).required()
}).with('name','url');
//almostShorty = {
// name = ,
// url =
// }
function create(almostShorty){
const result = Joi.validate(almostShorty, schema);
if(result.error === null){
return urls.insert(almostShorty);//Inserting the object in the Data Base.
}else{
return Promise.reject(result.error);
}
};
module.exports = {create};//Exporting the create function.
For example I have this URL: http://localhost/chat.html?channel=talk
How can I get the value of parameter channel in Node.js?
I want to store the value of channel in a variable.
I changed server.get to this:
server.get("/channel", (req, res) => {
let query = url.parse(req.url, true).query;
console.log(req.query.channel);
let rueckgabe = {
channel: req.query.channel
};
res.send(JSON.stringify(rueckgabe));
});
Now I'm expecting an output of the value of channel on my console but nothing appears.
This is the full code of index.js:
//Server erstellen
const express = require("express");
let server = express();
server.use(express.static("public"));
//Socket.io
const http = require("http");
let httpServer = http.Server(server);
const socketIo = require("socket.io");
let io = socketIo(httpServer);
//Eventlistener bei Verbindungsaufbau
io.on("connection", (socket) => {
console.log(socket.id);
socket.on("chatnachricht", eingabe => {
io.emit("nachricht", eingabe);
});
});
let stdIn = process.openStdin();
stdIn.addListener("data", (eingabe) => {
io.emit("nachricht", eingabe.toString());
});
server.get("/channel", (req, res) => {
let query = url.parse(req.url, true).query;
console.log(query);
let rueckgabe = {
channel: query.channel
};
//res.send(JSON.stringify(rueckgabe));
res.send(JSON.stringify(rueckgabe));
});
httpServer.listen(80, () => {
console.log("Server läuft");
});
SOLUTION
This code works so far but with limitations:
//Server erstellen
const express = require("express");
let server = express();
server.use(express.static("public"));
const http = require("http");
let httpServer = http.Server(server);
const socketIo = require("socket.io");
let io = socketIo(httpServer);
var router = express.Router();
const url = require("url");
var path = require('path');
//Eventlistener bei Verbindungsaufbau
io.on("connection", (socket) => {
console.log(socket.id);
socket.on("chatnachricht", eingabe => {
io.emit("nachricht", eingabe);
});
});
/*
let stdIn = process.openStdin();
stdIn.addListener("data", (eingabe) => {
io.emit("nachricht", eingabe.toString());
});
*/
server.get("/chat", (req, res) => {
let query = url.parse(req.url, true).query;
console.log(query.channel);
let rueckgabe = {
channel: query.channel
};
res.sendFile('chat.html', { root: path.join(__dirname, 'public/') });
//res.send(JSON.stringify(rueckgabe));
});
httpServer.listen(80, () => {
console.log("Server läuft");
});
Now it works with server.get() but I can't use both res.sendFile('chat.html', { root: path.join(__dirname, 'public/') }); and res.send(JSON.stringify(rueckgabe));. How can I use both?
It looks like you're using the Express framework for Node.
From the docs, query string params may be accessed via req.query:
server.get("/channel", (req, res) => {
let id = req.query.id; // where "id" is a paramter on the query string
}
And if you need the full URL of the request:
server.get("/channel", (req, res) => {
let fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
}
Well you mentioned for this url http://localhost/chat.html?channel=talk you're not seeing the channel parameter in the server. That's because you aren't hitting the endpoint that you've defined.
Copy of your code from above
server.get("/channel", (req, res) => {
let query = url.parse(req.url, true).query;
console.log(req.query.channel);
let rueckgabe = {
channel: req.query.channel
};
res.send(JSON.stringify(rueckgabe));
});
You're setting the /channel url here. With this configuration if you want to get the query parameter you need to call http://localhost:{portnumber}/channel?channel=somerandomvalue
If you want to have the /chat url change your configuration like this:
server.get("/chat", (req, res) => {
let query = url.parse(req.url, true).query;
console.log(req.query.channel);
let rueckgabe = {
channel: req.query.channel
};
res.send(JSON.stringify(rueckgabe));
});
and call into http://localhost:{portnumber}/chat?channel=somerandomvalue
If you want to serve a static html while using the url name as the same file name you can do something like this:
var router = express.Router();
var path = require('path');
router.get('/chat', function(req, res) {
// where chat.html is in the public directory
console.log(req.query.channel);
res.sendFile('chat.html', { root: path.join(__dirname, '../public/') });
});
How can i read cookie on node js ??
var socket = require( 'socket.io' );
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen( server );
var port = process.env.PORT || 8000;
var mysql = require('mysql');
function parseCookies (request) {
var list = {},
rc = request.headers.cookie;
rc && rc.split(';').forEach(function( cookie ) {
var parts = cookie.split('=');
list[parts.shift().trim()] = decodeURI(parts.join('='));
});
return list;
}
http.createServer(function (request, response) {
// To Read a Cookie
var user_id= cookies.realtimeid;
console.log(user_id);
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
var cookies = parseCookies();
console.log(cookies);
});
I am new on node and socket. I have to read cookie value that is set by codeignter.
How can i send header request on parseCookies from server.listen.
I see you are using express, so I suggest you to use the very well known module for it. cookie-parser https://www.npmjs.com/package/cookie-parser
Installation
npm install cookie-parser
HOW TO USE IT
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
So basically after your mysql require you can do app.use(cookieParser())
And then in every request you do in the req variable you will find the cookies with req.cookies
Example
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
app.get('/', function(req, res) {
console.log("Cookies: ", req.cookies)
})
app.listen(8080)