using domain name with expressjs on server rather than localhost - node.js

OK, so I am successfully running expressjs on windows iis server localhost:5000 and getting the expected json response using the following code...
server.js
const express = require('express');
var cors = require('cors')
const api_helper = require('./API_helper')
//const api_helper = require('./api')
const app = express();
const port = process.env.PORT || 5000;
require('ssl-root-cas/latest')
.inject()
.addFile('./root.crt')
.addFile('./****.crt')
// create a GET route
/* app.get('/express_backend', (req, res) => {
res.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' });
}); */
app.get('/express_backend', (req, res) => {
res.type('json')
api_helper.make_API_call('https://*my_api_server*/api/company/')
//api_helper.make_API_call('https://jsonplaceholder.typicode.com/todos/1')
.then(response => {
res.send(response)
})
.catch(error => {
res.send(error)
})
})
app.listen(port, () => console.log(`App listening on port ${port}!`))
API_helper.js
const request = require('request')
module.exports = {
/*
** This method returns a promise
** which gets resolved or rejected based
** on the result from the API
*/
make_API_call : function(url){
return new Promise((resolve, reject) => {
res.set('Content-Type', 'application/json');
request(url, { json: true }, (err, res, body) => {
if (err) reject(err)
resolve(body)
});
})
}
}
Screenshot of successful response using localhost:5000...
My question is, how would I get this to work using a domain name instead of localhost? When I use our https domain name, I get no response headers and just the raw html for server.js
Thanks.

When running on a port less than 1025, you need to run the server with escalated privileges.
If running on Windows ensure that your Command Line is running with Administrator Permissions.
With Linux:
sudo node server.js

Related

Redirect Next.js from http to https on Heroku

I have found many solutions to this question, but they all require either breaking SSR using a custom server, or breaking the API routes in Next.js. I need to redirect to https and still have SSR and API routes working.
I've tried using several variations of node and express custom servers and the nginx buildpack, none of which solved the criteria listed. The code below is the closest I've got to getting this to work. It works on the first load but then breaks on subsequent loads from non-secure http. This may also still break SSR.
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
createServer((req, res) => {
res.setHeader(
'strict-transport-security',
'max-age=31536000; includeSubDomains; preload'
);
if (req.headers['x-forwarded-proto'] === 'http') {
res.writeHead(301, { Location: `https://${req.headers.host}${req.url}` });
}
const parsedUrl = parse(req.url, true);
handle(req, res, parsedUrl);
}).listen(process.env.PORT, (err) => {
if (err) throw err;
console.log('> NextJS Server running...');
});
});
You can achieve this thing by Express integration. Next.js server can not help you in this thing completely at this point.
Express integration
const express = require('express')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
server.all('*', (req, res) => {
return handle(req, res)
})
server.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
Now using the heroku-ssl-redirect you can get the desired result.
Install heroku-ssl-redirect
npm install heroku-ssl-redirect
Now go into your server.js file and enter the following at the beginning:
const sslRedirect = require('heroku-ssl-redirect');
And then add this line below where express is implemented, but before the code that calls the GET route for the landing page :
app.use(sslRedirect());
It’s very important that you get the order right. Hope this solves your problem!

ERR_HTTP_HEADERS_SENT node js socket connection

I am building an API that uses socket connection to interact with a server backend built in C#. This is what I have so far
const request = require('request');
const express = require('express');
const app = express();
var server = require('http').createServer(app);
var cors = require("cors");
app.use(cors());
const net = require('net');
const client = new net.Socket();
const stringToJson=require('./stringToJson')
const port = process.env.PORT;
const host = process.env.HOST;
client.keepAlive=true
client.on('close', function() {
console.log('Connection closed');
});
app.get('/getScores',function (req,res) {
let dataSend=''
client.on('data', function (data) {
console.log('Server Says : ' + data);
if(data!='ANALYSIS-ERROR'){
dataSend=stringToJson.stringToJson(data)
}
else{
dataSend=stringToJson.stringToJson('0:0.0:0.0:0.0:0:0:0.0:0.0:0.0:0.0:0.0:0:0.0:0.0:0.0:0.0:0.0:0:0.0:0.0:0.0:0.0:0.0:0:0.0:0.0:0.0:0.0:0.0')
}
client.destroy()
return res.send(dataSend)
});
client.connect(port, host, function () {
client.write(`GENERAL-ANALYSIS|${req.query.id}|${req.query.website}|`)
return
});
return
})
app.get('/getPlace',function (req,res) {
console.log(req.query)
request(
{ url: `https://maps.googleapis.com/maps/api/place/textsearch/json?query=${req.query.name}+in+${req.query.city}&key=${process.env.API_KEY}` },
(error, response, body) => {
if (error || response.statusCode !== 200) {
return res.status(500).json({ type: 'error', message: error.message });
}
return res.json(JSON.parse(body));
}
)
})
//TODO ADD 404 500 PAGES
app.use((req, res, next) => {
res.status(404).send("Sorry can't find that!");
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
server.listen(9000, () => {
console.log(`App running at http://localhost:9000`);
});
Basically it creates a connection with the server and listens for some data to be sent back. Then processes the string and sends it to the React frontend. The api calls are made by the frontend using axios
It works but if you refresh the page it throws this error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
How do I fix this?
Try setting the headers as found in the documentation request.setHeader(name, value)
request.setHeader('Content-Type', 'application/json');

Expressjs server and external api calls

I'm new to frontend development and express server. When I tried to start an express.js server with react (with axios calls to external apis), it seems express.js is adding 'localhost:3000' in front of the external API calls so they fail.
In my server.js:
const path = require('path');
const express = require('express');
const app = express();
const publicPath = path.join(__dirname, '.', 'dist');
const port = process.env.PORT || 3000;
app.use(express.static(publicPath));
app.get('*', (req, res) => {
res.sendFile(path.join(publicPath, 'index.html'));
});
app.listen(port, () => {
console.log('Server is up!');
});
Which leads to the API call to www.example.com/api/ to become http://localhost:3000/www.example.com/api/
I also tried to filter the req by writing:
app.get('*', (req, res) => {
if (req.url.match(/\/api\//) === null) {
res.sendFile(path.join(publicPath, 'index.html'));
}
});
But it does not change things...
Can anyone help out this newbie that is me?
Update1 Adding the code for calling the api:
This is the api call:
const getSomething = () => {
try {
const url = endpoints.GET_SOMETHING;
return axios.get(url);
} catch (err) {
console.log(err);
}
};
endpoints.GET_SOMETHING is the api URL: www.example.com/api/getSomething
You need to put a / in the url
app.get('/*', (req, res) => {
res.sendFile(path.join(publicPath, 'index.html'));
});
and also your endpoint url should start with https://, http:// or //

How to Make API calls in express server

I am trying to make a get request in an express server, currently the server simply prints all post requests and it works fine up to that, the issue is when GET request is made the response is returned as 'undefined'
var env = process.env.NODE_ENV || "development";
var config = require("./config")[env];
const express = require("express");
const bodyParser = require("body-parser");
const axios = require("axios");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const hostname = config.server.host;
const port = config.server.port;
app.post("/", (req, res) => {
console.log(req.body);
res.sendStatus(200);
axios
.get("https://reqres.in/api/products/3")
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error.response);
});
});
app.listen(port, hostname, () =>
console.log(`Server running at http://${hostname}:${port}/`)
);
Use Postman to send Api calls to the server. I am attaching the link down below.
Install Postman chrome extension, if you're using chrome.
Use the Localhost:port server and post method and add variable to post your query
Hope this helps.
Moreover, Just add this tweak in your code and listen on a proper localhost,
var env = process.env.NODE_ENV || "development";
var config = require("./config")[env];
const express = require("express");
const bodyParser = require("body-parser");
const axios = require("axios");
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const hostname = config.server.host;
const port = config.server.port;
app.post("/", (req, res) => {
console.log(req.body);
res.sendStatus(200);
axios
.get("https://reqres.in/api/products/3")
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error.response);
});
});
app.listen(1337, function(){
console.log('Express listening on port', this.address().port);
});
Executed the below code
axios .get("https://reqres.in/api/products/3")
.then(response => { console.log(response); })
.catch(error => { console.log(error.response); })
Its executed and working fine.
My Guess is that in your case its going to catch block
Change the following line
.catch(error => {
console.log(error.response);
});
TO
.catch(error => {
console.log(error);
});
And see whether some error is printing.No response object is assigned to error, that may be u r receiving undefined

Node.js postman, sending JSON response to the client/browser

I am trying to learn node.js and I am stuck trying to send the JSON to the browser, I have not tried to consume the REST service because apparently the JSON is not being sent, it does not appear in postman.
This is my code:
Database connections pool
const mysql = require('mysql');
const pool = mysql.createPool({
host: "localhost",
database: "dbname",
user: "root",
password: "",
debug: true
});
module.exports.pool = pool;
Index
const Joi = require('joi');
const connections = require('./connections')
const express = require('express');
const app = express();
app.use(express.json());
function getClients() {
return new Promise((resolve, reject) => {
connections.pool.getConnection((error, connection) => {
connection.query("select * from clientes", (error, rows) => {
if(error) {
reject(new Error);
}
else {
resolve(JSON.stringify(rows));
}
})
connection.release();
})
});
}
app.get('/', (req, res) => {
getClients().then((rows) => {console.log(rows)})
.catch(err => err);
console.log(res);
res.end();
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`listening on port ${PORT}`));
In this part:
getClients().then((rows) => {console.log(rows)})
It logs the correct JSON response at the end however it calls a lot my attention that I am getting a very long server response before the JSON string.
when I use res.send(rows) it displays nothing, postman gives me 200 response and blank page.
I literally started learning NODEJS 3 days ago and I have been stuck with this for one day :(
You are not sending any data in response.
res.send does not send JSON it sends only string use res.json()
app.get('/', (req, res) => {
getClients()
.then((rows) => res.json(rows))
.catch(err => res.status(400).json(err));
});

Resources