How do I send image data from a url using express? - javascript

I want my the /image of my app to return a random image, how can I do that?
app.js:
const app = express();
app.get('/image', async (req, res) => {
const url = 'https://example.com/images/test.jpg';
res.send(/**/); // How do I send the image binary data from the url?
});
index.html
In HTML, this image actually shows the content of the image https://example.com/images/test.jpg
<img src="https://my-app.com/image" />

We have the same problem, and this is my solution for this using request package, so you have to yarn add request or npm i request first.
your code should be like this
const request = require('request');
const express = require('express');
const app = express();
app.get('/image', async (req, res) => {
const url = 'https://example.com/images/test.jpg';
request({
url: url,
encoding: null
},
(err, resp, buffer) => {
if (!err && resp.statusCode === 200){
res.set("Content-Type", "image/jpeg");
res.send(resp.body);
}
});
});

There is res.sendFile in Express API
app.get('/image', function (req, res) {
// res.sendFile(filepath);
});

const express = require("express");
const https = require("node:https");
const app = express();
const port = 3000
app.get("/", function(req, res){
const url = "https://api.openweathermap.org/data/2.5/weather?q=Paris&units=metric&appid=65441206f989bc53319e2689fccdc638";
https.get(url, function(response){
response.on("data", function(data){
const weatherData = JSON.parse(data)
const icon = weatherData.weather[0].icon
const imageUrl = "http://openweathermap.org/img/wn/" + icon + "#2x.png"
res.write("<img src=" + imageUrl + " ></img>")
res.send();
})
});
})

You can save all such image links in json or any of your choice data file and get from them randomly and forward and pass them through variable in response. Like: res.send(imgURL: 'https://example.com/images/test.jpg'); or you can pass url variable in init.

Related

downloaded file corrupted by getting response using node.js and express

I want to download zip file by response using Node.js and express. I could downloaded it but it coruppted. I made 2 servers, one is for data storing and the other is front-end. I can't put the zip file on front-end server so I need to get it by response. following is the code:
for frontend (front-end-server)
const express = require("express");
const app = express();
const http = require('http');
const server = http.createServer(app);
const request = require('request');
app.get("/api/download", (req, res) => {
request('http://192.168.10.888:8088/getfile', (error, response, body) =>
{
res.set({
'Content-Type': 'application/zip',
'Content-Disposition': 'attachment; filename="sample.zip"'
});
res.send(body);
});
});
app.get('/', (req, res) => res.send('Hello app'));
app.listen(8081, () => console.log('Listening on port 8081'));
for data storing (data-server)
var fs = require('fs');
var http = require('http');
const express = require("express");
const app = express();
app.get('/getfile', function (req, res)
{
res.sendFile("/data/sample.zip");
});
app.get('/', (req, res) => res.send('Hello'));
app.listen(8088, () => console.log('Listening on port 8088'));
data-server just return the file as stream and front-end-server get it by http-request and return it to browser so I expected download the zip file by simply type following URL
http://192.168.10.97:8081/api/download

JSON data not defined

I tried to make a food recipe app and wrote this code using node:
const express = require("express");
const bodyParser = require("body-parser");
const https = require("https");
const app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res) {
const numberOfRecipes = req.body.totalRecipes;
const apiKey = "apiKey...";
const url = "https://api.spoonacular.com/recipes/random?apiKey=" + apiKey + "&number=" + numberOfRecipes;
https.get(url, function(response) {
response.on("data", function(data) {
const recipeData = JSON.parse(data);
// console.log(recipeData);
// console.log(data);
const title = recipes[0].title;
res.write("<h1>The title of the recipe is " + title + ".</h1>");
res.send();
})
});
});
app.listen(3000, function() {
console.log("The server started at port 3000");
});
But the terminal says
C:\Users\ArunBohra\Desktop\food-recipes\app.js:23
const recipeData = JSON.parse(data);
^
ReferenceError: data is not defined
at ClientRequest. (C:\Users\ArunBohra\Desktop\food-recipes\app.js:23:41)
Can anyone help me with this?
I think your not accessing that API content right. Try this :
axios.get('https://api.github.com/users/mapbox')
.then((response) => {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});
find a popular third-party library like Axios or others and use that to make API calls. then do console logs that will you
refer this one How do I use axios within ExpressJS?
and this one ReferenceError: request is not defined

Express.js: Undefined request body (base64)

I'm trying to convert the .xls table to .csv row.
I found the library that helps with such operation, its name XLSX
As the first step, I encode .xls table to base64 format.
Now I'm trying to send the post request with Postman (with base64 code as the body of the request)
But when I'm trying to console.log my req.body, I'm receiving undefined. Can you tell me where I could make a mistake in my app?
my app.js:
const express = require('express');
const dataConverter = require('./inputDataConverter');
const { errorHandler } = require('./../error/error-handler');
const app = express();
const port = process.env.PORT || 5000;
const domain = process.env.DOMAIN || '0.0.0.0';
app.post('/convert', dataConverter);
app.all('*', (req, res, next) => next('Invalid request'));
app.use(errorHandler);
app.listen(port, () => {
console.log(`Microservice runs on http://${domain}:${port}`);
});
inputDataConverter.js:
const XLSX = require('xlsx');
module.exports = (req, res, next) => {
console.log('First console.log ' + req.body);
const getWorkbook = (data) => {
let wb = null;
if (!data.type || data.type === 'base64') {
wb = XLSX.read(data.body, { type: 'base64' });
}
console.log('everything is working');
return wb;
};
const requestData = req.body;
console.log(requestData);
getWorkbook(requestData);
};
As Molda said
You may need body parser
https://www.npmjs.com/package/body-parser
On new version actually body-parser is embedded to express so you can use that like:
app.use(express.json())
I really suggest you use express-generator package to generate base Express application
https://www.npmjs.com/package/express-generator
You may find something you may not need
just strip that out

How to get value of URL parameter in Node.js?

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/') });
});

Loading JSON files during Express app initialization

I have a movie-finding app that makes API calls in the backend. During initialization I need to load some JSON files: one (lang.json) contains a list of languages for searching purposes, the other (stored in the config variable) is used to get a link to the movie poster.
How would I ensure the loading of these files is completed before an HTTP request is made? One solution I can think of involves putting the calls to app.get() and app.listen() inside fs.readfile()'s callback. But is there a better way? Web development is totally new to me.
var express = require('express');
var app = express();
var fs = require('fs');
var request = require('request');
var merge = require('merge');
require('dotenv').config();
var apiKey = process.env.API_KEY;
var config = {};
app.use(express.static('view'));
// TODO load config and lang before below code
app.get('/lang', function(req, res) {
fs.readFile('lang.json', function(err, data) {
if (err) throw err;
res.json(JSON.parse(data));
});
});
app.get('/genres', function(req, res) {
request.get({
url: 'http://api.themoviedb.org/3/genre/movie/list',
qs: {api_key: apiKey}
}, function(error, response, body) {
res.json(JSON.parse(body).genres);
});
});
app.get('/randomMovie', function(req, res) {
request.get({
url: 'https://api.themoviedb.org/3/discover/movie',
qs: merge(req.query, {api_key: apiKey})
}, function(error, response, body) {
body = JSON.parse(body).results;
var len = body.length;
var i = Math.floor(Math.random() * len);
var movie = body[i];
// movie.poster_path = movie.images.base_url + movie.images.poster_sizes[6] + movie.poster_path;
res.json(movie);
});
});
app.listen(3000, function() {
console.log('server started on port 3000');
});
The easiest way is to just use fs.readFileSync() before your call to app.listen(). For example:
var lang = fs.readFileSync('lang.json');
app.get('/lang', function(req, res) {
res.setHeader('Content-Type', 'application/json');
res.send(lang);
});
// ...
Just be aware that the contents of lang will not automatically update if the contents of lang.json change on disk during the lifetime of your node process.

Categories

Resources