I am using the below code and I am using express-http-proxy:
const express = require('express');
const proxy = require('express-http-proxy');
var baseUrl2 = "https://localhost:5002";
var app = express();
app.use('/api', proxy(baseUrl2, {
// I want to change the baseUrl2 before making the request.
proxyReqPathResolver: (req) => {
const modifiedURL = "/someChanges"
return require('url').parse(modifiedURL).path;
},
}));
app.listen(3000);
I am able to change the url from https://localhost:5002 to https://localhost:5002/someChange.
But I need to change it from https://localhost:5002 to https://localhost:5001 or https://example.com.
I was able to change the port using proxyReqOptDecorator option. I am changing port using proxyReqOpts.port but we can also change the host using proxyReqOpts.host
Updated Code:
const express = require('express');
const proxy = require('express-http-proxy');
var baseUrl2 = "https://localhost:5002";
var app = express();
app.use('/api', proxy(baseUrl2, {
// I want to change the baseUrl2 before making the request.
proxyReqPathResolver: (req) => {
const modifiedURL = "/someChanges"
return require('url').parse(modifiedURL).path;
},
proxyReqOptDecorator: (proxyReqOpts, srcReq) => {
if(someCondition)
proxyReqOpts.port = 5001;
else
proxyReqOpts.port = 5002;
return proxyReqOpts;
}
}));
app.listen(3000);
Related
Express App showing cannot find after deploying on cPanel. I have tried to sort out this issue also when I write server.listen() it works great but when I write app.listen() it gives cannot find message.
I tried default Node Js code (last 10 lines except app.listen() ) which works fine while app.listen() not working:
const express = require("express");
const multiparty = require('multiparty');
const mongoose = require("mongoose");
const morgan = require('morgan');
const { createHttpTerminator } = require('http-terminator');
const fs = require('fs');
const cors = require('cors');
const crypto = require('crypto');
require('dotenv').config();
const { MongoClient, ServerApiVersion } = require('mongodb');
const {Product, Service, Home, HireMe } = require('./models/Product');
const app = express();
app.use(morgan('tiny'));
app.use(express.static('public'));
app.use(express.json());
app.use(cors());
app.get('/', (req, res) => {
res.send('Home Page...!');
});
app.get('/offers', async (req, res) => {
try {
const result = await Product.find({});
res.send("result");
} catch (err) {
res.send({ 'error': err.message });
}
})
var http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var message = 'It works!\n',
version = 'NodeJS ' + process.versions.node + '\n',
response = [message, version].join('\n');
res.end(app);
});
server.listen(); //It works
app.listen (); // Showing Cannot find message
I solved this error by prefixing the URL link (on which I created node JS on cPanel) to routes. Now it works great.
i am trying to return the value of my search after using the node-spotify-api package to search for an artist.when i console.log the spotify.search ..... without the function search function wrapped around it i get the values on my terminal..what i want is when a user sends a request to the userrouter routes i want is to display the result to the user..i using postman for testing ..
This is the controller
const Spotify = require('node-spotify-api');
const spotify = new Spotify({
id: process.env.ID,
secret: process.env.SECRET,
});
const search = async (req, res) => {
const { name } = req.body;
spotify.search({ type: 'artist', query: name }).then((response) => {
res.status(200).send(response.artists);
}).catch((err) => {
res.status(400).send(err);
});
};
module.exports = {
search,
};
**This is the route**
const express = require('express');
const searchrouter = express.Router();
const { search } = require('./spotify');
searchrouter.route('/').get(search);
module.exports = searchrouter;
**This is my server.js file**
const express = require('express');
require('express-async-errors');
const app = express();
require('dotenv').config();
// built-in path module
const path = require('path');
// port to be used
const PORT = process.env.PORT || 5000;
// setup public to serve staticfiles
app.use(express.static('public'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.set('port', PORT);
const searchrouter = require('./route');
app.use('/search', searchrouter);
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'index.html'));
});
app.listen(PORT, (req, res) => {
console.log(`Server is listening on port ${PORT}`);
});
[that is my project structure][1]
Well Your Code has a bug
Which is
searchrouter.route('/').get(search);
You are using a get request and still looking for a req.body
const { name } = req.body;
name is going to equal to = undefined
and when this runs
spotify.search({ type: 'artist', query: name })
it's going to return an empty object or an error
req.body is empty for a form GET request
So Your fix is
change your get request to a post
searchrouter.route('/').post(search);
I'm working on a project that involves an application built with Electron that interfaces with an express server, running on Localhost or the home network.
Problem right now is, I'm having trouble getting the server to acknowledge any requests from the application.
Here is my front end logic in the electron application:
let ipAddress;
let port;
let requestAddress;
function connect(){
const ipField = document.getElementById("nu-ip").value;
const portField = document.getElementById("nu-port").value;
port = portField;
if (ipField === "") {
ipAddress = 'localhost';
} else {
ipAddress = ipField;
}
port = portField;
if(port === ""){
requestAddress = `http://$(ipAddress)`;
} else {
requestAddress = `http://${ipAddress}:${port}`;
};
alert(requestAddress);
const request = newXMLHttpRequest();
alert(requestAddress);
request.open("GET",`${requestAddress}/connect`).send();
request.onReadyStateChange = (res) => {
alert(res);
}
}
function startup() {
console.log('Hey where does this show up?')
const NuToggle = document.getElementById("NuHelper-enable");
const NuTools = document.getElementById("Nu-tools");
const connectButton = document.getElementById("connect-button");
NuToggle.addEventListener("change", (event) => {
if(event.target.value === 'enable'){
//alert("NuHelper has been enabled");
NuTools.style.display='block';
connectButton.addEventListener('click', connect);
}
})
}
window.onload = startup;
And here is my server:
//require in our basic dependencies
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const errorHandler = require('errorhandler');
const cors = require('cors');
const PORT = 80;
const app = express();
app.use(morgan('dev'));
app.use(bodyParser);
app.use(errorHandler);
app.use(cors());
app.get('/connect',(req, res, next) => {
res.sendStatus(200);
})
app.listen(PORT, () => {
console.log(`Nu is listening on PORT ${PORT}`);
})
I put 80 into the PORT input and it'll alert "http://localhost:80", but it'll get no response at all from the server, and my logging middleware won't acknowledge that it received any request at all, which makes me think that I'm sending the request to the wrong address. Thanks in advance to anyone who understands how to solve this!
I'm using the official i18n library to localize my Angular Universal app and am using a proxy to serve the localized versions.
My app works fine as long as there is a language present in the url (e.g: /en/page), but doesn't work otherwise (e.g: / or /page). I get the error Cannot GET / whenever I try to access a page without the locale in the url.
How do I redirect the user to the localized version of the page using the accept-language header of the request? If I try it with the code below, it creates a redirect loop and the page doesn't load.
server.run.js
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
function app() {
const server = express();
server.use(cookieParser());
server.use('/', (req, res, next) => {
const languages = ['en', 'de', 'fr'];
languages.forEach((locale) => {
const appServerModule = require(path.join(__dirname, locale, 'main.js'));
server.use(`/${locale}`, appServerModule.app(locale));
});
locale = (req.headers['accept-language'] || '').substring(0, 2);
if (!languages.includes(locale)) {
locale = 'en';
}
res.redirect(`/${locale}`)
});
return server;
}
function run() {
app().listen(4200, () => {
console.log(`Node Express server listening on http://localhost:4200`);
});
}
run();
I managed to solve it like this:
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
function app() {
const server = express();
server.use(cookieParser());
const languages = ['en', 'de', 'fr'];
languages.forEach((locale) => {
const appServerModule = require(path.join(__dirname, locale, 'main.js'));
server.use(`/${locale}`, appServerModule.app(locale));
});
server.get('/(:locale(en|fr|de)/)?*', (req, res, next) => {
const { urlLocale } = req.params;
const userLocale = (req.headers['accept-language'] || '').substring(0, 2);
if (urlLocale !== userLocale) {
res.redirect(userLocale + req.url);
}
});
return server;
}
function run() {
app().listen(4200, () => {
console.log(`Node Express server listening on http://localhost:4200`);
});
}
run();
I have this in Google's App Engine (node.js).
My device gets all the commands but I still get the Could not send command. Is the device connected? error.
BTW, already tried this: Await for function before end()
And same result.
Trying to follow this example BTW:
https://cloud.google.com/nodejs/docs/reference/iot/0.2.x/v1.DeviceManagerClient#sendCommandToDevice
const express = require('express');
var bodyParser = require('body-parser');
const app = express();
var urlencodedParser = bodyParser.urlencoded({
extended: false
})
const iot = require('#google-cloud/iot');
app.get('/', urlencodedParser, (req, res) => {
res.setHeader('Content-Type', 'application/json');
const projectId = req.query.proyecto;
const cloudRegion = req.query.region;
const registryId = req.query.registro;
const numSerie = req.query.numSerie;
const command = req.query.command;
const client = new iot.v1.DeviceManagerClient();
if (client === undefined) {
console.log('Did not instantiate client.');
} else {
console.log('Did instantiate client.');
sendCom();
}
async function sendCom() {
const formattedName = client.devicePath(projectId, cloudRegion, registryId, numSerie)
const binaryData = Buffer.from(command);
const request = {
name: formattedName,
binaryData: binaryData,
};
return client.sendCommandToDevice(request).then(responses => res.status(200).end(JSON.stringify({
data: OK
}))).catch(err => res.status(404).end('Could not send command. Is the device connected?'));
}
});
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
module.exports = app;
On my end I should get status 200 and OK but it doesn't happen.