This may be a somewhat stupid question but how would I pass a url into express url params array. When I try a youtube link half of it is cut off. For example 'https://www.youtube.com/watch?v=iik25wqIuFo' comes out as 'https://www.youtube.com/watch'. Thanks for any help. Heres my code:
const express = require('express');
const url = require('url');
const app = express();
const fs = require('fs')
const youtubedl = require('youtube-dl')
function downloadvideo(link) {
const video = youtubedl(link,
['--format=18'],
{ cwd: __dirname })
video.on('info', function(info) {
console.log('Download started')
console.log('filename: ' + info._filename)
console.log('size: ' + info.size)
})
video.pipe(fs.createWriteStream('myvideo.mp4'))
};
app.get('/', function (req, res) {
res.send('Hello Express app!');
});
app.get('/download/video/:id', function (req, res) {
app.use(express.urlencoded({ extended: true }));
res.send('Downloading ' + req.params.id);
});
app.get('/download/subtitle/:id', function (req, res) {
res.send('user ' + req.params.id);
});
app.get('/download/playlist/:id', function (req, res) {
res.send('user ' + req.params.id);
});
app.listen(3000, () => {
console.log('server started');
});
To pass in text with special characters like ?, you must first run it through a function like encodeURIComponent() which essentially makes these special characters' URL safe. So first step is to make the parameter URL safe by running it through encodeURIComponent() (or you could escape special characters manually which is not fun):
console.log(encodeURIComponent('https://www.youtube.com/watch?v=iik25wqIuFo'));
// result: "https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Diik25wqIuFo"
Then pass it into your URL as a query parameter.
yourAppUrl.com/path?youtubeLink=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Diik25wqIuFo
Related
I'm trying to replicate the functionality of bashupload.com but using node. I want the simplicity of just doing curl host -T file but I ran into some problems because I can't seem to understand how to read the PUT file. Curl uses a PUT request when you use the -T option, so it has to be PUT.
I tried using packages like multiparty:
receiveAndUploadFile: function (req, res) {
var multiparty = require('multiparty');
var form = new multiparty.Form();
// var fs = require('fs');
form.parse(req, function(err, fields, files) {
console.log('The files', files)
console.log('The fields', fields)
})
res.send("Okay, bye.")
}
But this prints undefined values for files and fields.
I also tried using express-fileupload middleware
app.use(fileUpload({}));
but still, if I try to print req.files then I will get undefined.
Is there any specific way to read the file?
Thanks a lot!
This is my main file, index.js::
const express = require("express");
const path = require("path");
const app = express();
const port = 8080;
const tools = require("./tools");
const fileUpload = require("express-fileupload");
app.use(fileUpload());
app.use(express.static(__dirname + "/assets"));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname + "/index.html"));
});
app.get("/f", (req, res) => {
res.send("This route is only available as a POST route.");
});
app.put("/f", tools.receiveAndUploadFile);
app.listen(port, () => {
console.log(`Server started listening on port: ${port}`);
});
And the tools.js file:
const fs = require("fs");
const path = require("path");
module.exports = {
receiveAndUploadFile: function (req, res) {
console.log("Files: ", req.files);
res.send("Okay bye");
},
};
This is printing "Files: undefined" to the console.
A PUT and a POST are effectively the same thing. To upload arbitrary data, just read the data stream and write it to a file. Node provides a .pipe method on streams to easily pipe data from one stream into another, for example a file stream here:
const fs = require('fs')
const express = require('express')
const app = express()
const PORT = 8080
app.get('/*', (req, res) => res.status(401).send(req.url + ': This route is only available as a POST route'))
app.put('/*', function (req, res, next) {
console.log('Now uploading', req.url, ': ', req.get('content-length'), 'bytes')
req.pipe(fs.createWriteStream(__dirname + req.url))
req.on('end', function () { // Done reading!
res.sendStatus(200)
console.log('Uploaded!')
next()
})
})
app.listen(8080, () => console.log('Started on :8080'))
If you do a PUT to /file.mp4, it will upload all the data over to the script dir (__dirname) + the URL file path.
via curl, curl http://localhost:8080/ -T hello.txt
When I land on the home page I add a query string to the URL and then I redirect to that URL.
app.get('/', (req, res) => {
let room = Math.floor(Math.random() * 1000);
console.log(room);
res.redirect('/views/index.html?room=' + room);
})
but then i would like to access the query string from the other page but can't quite figure out why this is not working:
app.get('/views/index.html', (req, res) => {
console.log('heu ' + req.query.room)
})
I've tried to change the path but nothing seems to be working.
Any help would be appreciated. :)
EDIT: full server.js
const express = require('express')
const app = express()
const server = require('http').Server(app);
app.use(express.static('./'))
app.get('/', (req, res) => {
let room = Math.floor(Math.random() * 1000);
console.log(room);
res.redirect(`/views/index.html?room=${room}`);
})
app.get('/views/index.html', (req, res) => {
console.log('hey ' + req.query.room)
})
server.listen(1337, function () { });
server.js is in the main folder, then I have a sub-folder (views) containing the index.html page
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var port = 3000;
const fs = require('fs');
// we are connecting to the mangodb using mangoose
var mongoose = require("mongoose");
// Now we are using bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect("mongodb://localhost:27017/YourDB", { useNewUrlParser: true })
// now we are creating the schema to the database
var nameSchema = new mongoose.Schema({
firstName: String,
lastNameName: String
});
// Now we have to create a model
var User = mongoose.model("User", nameSchema);
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
// Now we are posting the data
app.post("/addname", (req, res) => {
console.log("nnnnnn")
console.log(req.body.firstName)
var myData = new User(req.body);
myData.save()
console.log(myData);
fs.writeFile(__dirname +"/data.json",myData, function(err){
if(err) {
return console.log(err);
}
console.log("The file is saved ");
})
console.log(myData)
})
// Now we are getting the data
app.listen(port, () => {
console.log("Server listening on port " + port);
});
1)I am using express app.post to post the data into database and store the data into the write file to check
2) app.post is not working it tried console.log to check but it is not going inside the function
3) I am not getting output as well as any error plese help me
there is no error handling and response handling in this code.
it will be readable if we write post method with async/await :
app.post("/addname", async (req, res) => {
console.log("nnnnnn")
console.log(req.body.firstName)
var myData = new User(req.body);
await myData.save()
console.log(myData);
fs.writeFileSync(__dirname +"/data.json", myData)
console.log(myData)
})
you will add next() to app.use
var User = mongoose.model("User", nameSchema);
app.use("/", (req, res,next) => {
res.sendFile(__dirname + "/index.html");
next()
});
// Now we are posting the data
app.post("/addname", (req, res) => {
console.log("nnnnnn")
console.log(req.body.firstName)
var myData = new User(req.body);
myData.save()
console.log(myData);
fs.writeFile(__dirname +"/data.json",myData, function(err){
if(err) {
return console.log(err);
}
console.log("The file is saved ");
})
console.log(myData)
})
// Now we are getting the data
app.listen(port, () => {
console.log("Server listening on port " + port);
});
That's because every request is going to this app.use code block. app.use("/", (req, res) => { ... });
Just Put it below the app.post("/addname", (req, res) => { ... });
app.use is used to mount middlewares into the request-response chain. So, every request that comes matches the /(which is essentially every request) goes inside that middleware. So, use your routes first then use the middleware at the end.
EDIT:
Let me give you a mcve which I tested locally:
const express = require('express');
const fakeData = function(){
return {
s: "fakeData"
}
}
const app = express();
const port = 8181
const path = require('path')
app.get("/a", (req, res) => {
return res.json({d:'yay'});
});
app.use('/',(req,res)=>{
return res.json(fakeData());
})
app.listen(port, () => {
console.log(`Server started on PORT ${port}`);
});
Because every request goes through a mounted middleware, so when you GET/POST/ANYTHING to localhost:8181/<abosulutely_any_path> it will go through the app.use because it treats that function as middleware and will return { s: "fakeData" }.
But when you make a GET call http://localhost:8181/a it will go to the app.get route BECAUSE WE DECLARED IT FIRST and return { d : "yay" }
I'm trying to capture the parameter values from the callback URL coming from the Fitbit API.
The call back URL looks like below,
http://localhost:9000/callback#access_token=********&user_id=*******&scope=sleep+settings+nutrition+activity+social+heartrate+profile+weight+location&token_type=Bearer&expires_in=30418415
I have stated by callback URL in the fitbit API as http://localhost:9000/callback.
My ExpressJS code is as below.
const express = require('express');
const morgan = require('morgan');
const path = require('path');
const app = express();
app.use(morgan(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] :response-time ms'));
app.use(express.static(path.resolve(__dirname, '..', 'build')));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'build', 'index.html'));
});
const PORT = process.env.PORT || 9000;
app.get('/callback', function(req, res) {
var access_token = req.param('access_token') || null;
var user_id = req.param('user_id') || null;
res.send(access_token + ' ' + user_id);
});
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}!`);
});
I can't figure out where the problem is.
The # symbol in an URL is to introduce framgent identifier. So your callback url http://localhost:3000/callback#access_token=********&user_id=*******&scope=sleep+settings+nutrition+activity+social+heartrate+profile+weight+location&token_type=Bearer&expires_in=30418415 will only get the http://localhost:3000/callback not sending any parameters to your server. So, you can not get these parameters in your server directly.
However there is solution to this. Please refer to this answer.
req.param('token') is depreciated use req.params.token pass the value directly into the url
if you are using req.params specify you key params in the url
app.get('/callback/:access_token/:user_id', function(req, res) {
//url ==> localhost:9000/callback/1233/123
var access_token = req.params.access_token || null;
var user_id = req.params.user_id || null;
console.log(req.params)
res.send(access_token + ' ' + user_id);
});
if you want the catch the value in the url means use req.query instead of req.params pass the value using the key of req.query
app.get('/callback',function(req, res) {
var access_token = req.query.access_token || null;
var user_id = req.query.user_id || null;
console.log(req.query);
res.send(access_token + ' ' + user_id);
});
I am using express 3. I have a GET route in my code which does not match if I do not place a * wildcard at the end
var express = require('express');
var app = new express();
app.get('/image/upload', function(req, res) {
console.log(req.params);
res.send("ok");
});
var port = 3002;
app.listen(port);
console.log("Image Get Server started on port " + port);
The code is as above. The URL that I am trying to hit is
http://localhost:3002/image/upload/imageId.jpg
The response that I get is Cannot GET /image/upload/imageId.jpg
However when I place a wildcard at the end of the route to match
app.get('/image/upload*', function(req, res) {
it works. I remember the routes working without such wildcards. What is it that I am missing in this?
you may try:
app.get('/image/upload/:name', function (req, res)
{
var name = req.params.name;
try{
res.send("OK");
}
catch(err){
console.log("Error on: "+name+err);
}
});
it works at my node, but not sure if it is compatible with express 3