I am trying to pipe an image response from an internal API, using NodeJS Express to an external endpoint. I.e. proxying an image.
This is what I have tried, but I keep getting an empty box instead of the image:
app.get('/image', (req, res) => {
res.setHeader('Content-Type', 'image/png');
request.get(`http://localhost:8080/image`).pipe(res);
// Also tried reading from a file and not the endpoint
//to make sure it's not a problem with "request" library with same results
//fs.createReadStream('./image.png').pipe(res);
});
Using browser dev tools I can also see that the size of the empty image I get on the external endpoint is bigger then that of the working image got from the internal endpoint.
Accessing the endpoint from "Postman" seems to give the image without problems, but accessing from Firefox says that the image has errors.
So it seems to be some kind of an encoding issue which I can't seem to figure out how to fix. Please help.
Can't reproduce your issue. The below example works fine. Testing environment:
Microsoft Edge 86.0.622.38
E.g.
server-internal.ts:
import express from 'express';
import fs from 'fs';
import path from 'path';
const app = express();
const port = 8080;
app.get('/image', (req, res) => {
console.log('internal server /image');
res.setHeader('Content-Type', 'image/png');
fs.createReadStream(path.resolve(__dirname, './image.png')).pipe(res);
});
app.listen(port, () => console.log('HTTP server is listening on port:', port));
server-external.ts:
import express from 'express';
import request from 'request';
const app = express();
const port = 3000;
app.get('/image', (req, res) => {
console.log('external server /image');
res.setHeader('Content-Type', 'image/png');
request.get(`http://localhost:8080/image`).pipe(res);
});
app.listen(port, () => console.log('HTTP server is listening on port:', port));
Access http://localhost:3000/image, got the image correctly.
The logs of the internal server:
HTTP server is listening on port: 8080
internal server /image
The logs of the external server:
HTTP server is listening on port: 3000
external server /image
source code: https://github.com/mrdulin/expressjs-research/tree/master/src/stackoverflow/64302729
Thank you slideshowp2 for taking your time and pointing out that, my provided code should indeed work.
It would have been impossible to figure out the issue with the info that I gave.
I was using "livereload" middleware in my project.
This middleware intersects all the responses coming from my server and tries to inject the liverelad script into them.
By default it is configured to ignore responses for endpoints ending with ".png" and other image and binary formats.
Adding ".png" to the endpoint path, solved the issue.
app.get('/image.png', (req, res) => {
request.get(`http://localhost:8080/image`).pipe(res);
});
Related
I have an express server in NodeJS. It has a POST request with console.logs inside of it. Where Can I find the console.logs?
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
const PORT = 5000;
app.get('/', (req, res) => {
console.log("this appears in the browser");
});
app.post('/login', (req, res) => {
console.log("where do I see this text??");
});
app.listen(PORT, '0.0.0.0', function() {
console.log("Server started (this text appears in the terminal)");
});
I'm running the server from Command Prompt. console.logs that aren't within a request appear in it. Where do the console.logs in the POST request function appear? I ask because I would like to see what's going on with the logic inside a more sophisticated POST request.
When you run the Node.js server directly from cmd, it should start the server and listening to the port specified. Now, when you start to hit the route/s all the console.log o/p to the terminal window not to the browser console window. Check the image for reference.
It will appear in the same terminal that you put the server to run.
I'm running a NodeJS application and am visiting it at localhost/?product=test. I want to retreive 'test' (or any URL-related information for that matter).
Google shows me 2 options, but I can't get either to work:
Use HttpRequest
const http = require('http');
const url = require('url');
http.createServer(function (req, res) {
const queryObject = url.parse(req.url,true).query;
console.log(queryObject);
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Feel free to add query parameters to the end of the url');
}).listen(3000);
I'm trying to use this code, or variations on it, but the issue is that I cannot create a server to listen to because the address is already in use. I'm not too familiar with NodeJS, but what I don't understand is how to use a HttpRequest properly to listen to the running application and get its URL.
Use Express
Using express doesn't give an error, but all code snippets that -should- work return undefined for me when retrieving the URL.
What is a simple way to retrieve the URL the user used to visit my NodeJS app, so I can retrieve the parameters?
If you want to access localhost without filling in a port like here localhost/?product=test then you should listen to port 80 and not 3000. Otherwise your request should look like this: localhost:3000/?product=test
You should also create a route method for products. In express it will look like this:
const express = require('express')
const app = express()
const port = 80
app.get('/', (req, res) => res.send('home'))
app.get('/product/:productId', function (req, res) {
res.send(req.params)
})
app.listen(port, () => console.log(`Listening on port ${port}!`))
If you run this example your request url should be http://localhost/product/test and response will look like
{
"productId": "test"
}
I am sending a JSON response from Node.js server to a Slack App.
This response is displayed in raw form, as JSON, instead of being formatted properly.
Minimum code that replicates the problem:
server.js:
const express = require('express');
const app = express();
// POST request processing
app.post('/', function(req, res){
var arr1 = [{"type":"section","text":{"type":"mrkdwn","text":"*Lorem Ipsum*"}},
{"type":"section","text":{"type":"mrkdwn","text":"_Lorem Ipsum_"}},
{"type":"section","text":{"type":"mrkdwn","text":"`Lorem Ipsum`"}}]
res.setHeader('Content-Type', 'application/json');
res.json(arr1);
});
// Listen to the AppEngine/Heroku - specified port, or 8080 otherwise
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log('Server listening on port ${PORT}...');
});
The JSON message should be rendered like visible here:
api.slack.com/tools/block-kit-builder
Instead, it is displayed like this:
I have also tried this and numerous other ways:
res.end(JSON.stringify(arr1));
I've found this proper-way-to-return-json-using-node-or-express on SO, and looked through Slack and Node.js documentation. I've advanced quite far in my app, but responses are still not rendered properly, so I figured I would ask here.
Any ideas?
please use a simple express response res.send(your JSON object);
I am trying to cache a file client side with NodeJs and Express.
Here an example of what I am trying to do :
const path = require('path');
const express = require('express')
const app = express()
app.get('/', (req:any, res:any)=> res.send('Hello World!') );
app.get('/file', (req:any, res:any)=> {
console.log('Request URL:', req.originalUrl);
res.set('Cache-Control', 'public, max-age=60');
res.sendFile(path.resolve(__dirname+'/../file.pdf'));
});
app.listen(3000, ()=>console.log('Example app listening on port 3000!') );
Then I browse the file twice and I expect to have only one log Request URL: /file. But with this code I got two. It seems that either my Cache-Control headers is ignored by the browser or it get mixed up with default Express behavior like ETag..
Any Idea ?
I'm not sure but first thing that I thought about was the file size.
Maybe it is too big?
what-is-chrome-default-cache-size-limit
I try to run simplest Express code on Cloud server
var express = require('express');
var app = express();
app.get('/test', (req, res) => res.send('Hello '));
app.listen( 3000 );
I am getting the Apache 404 error : GET /cood180119/projExpress1/demo1/test HTTP/1.0, Cannot GET /cood180119/projExpress1/demo1/test
I have noticed that my url is http://77.xx.xx.xx/cood180119/projExpress1/demo1/test
while error logs shows IP : 88.xx.xx.xx.
How to resolve?
I have a node hello world example, which is working with the following url:
http://77.xx.xx.xx/node-hello-world-master/
where the file is in public_html/node-hello-world-master/app.js,
but does not work with http://77.xx.xx.xx:3000/
const http = require('http');
http.createServer(function(request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end("Hello, World!\n port= ' + process.env.PORT);
}).listen(process.env.PORT); //is says that port is undefined
I set the port=3000 in environmental node variables.
After this, i can get the port number echoed , but i still can not access webpage using ttp://77.xx.xx.xx:3000/
Seems firewall is configured wrong.
I think you are requesting the wrong URL.
app.get('/test', (req, res) => res.send('Hello '));
app.listen( 3000 );
this will always produce a route as follows
'http://ip:3000/test
why do you use cood180119/projExpress1/demo1 in your URL. I don't see any route defined for that.
Your route
app.get('/test', (req, res) => res.send('Hello '));
make sure that the URI (or the path in this case /test) of the request you want to capture exists.
My problem:
The name of html file was not exactly "index.html"
So, I renamed it and it worked perfectly!
app.use(express.static('public'));
Note: public is a folder inside my server directory witch contains index.html and styles.css.