How do you use an api key in Node.js? - node.js

I am using both express and request, but when I try to enter the URI into the request, the console says ' Invalid URI "api.openweathermap.org/data/2.5/weather?q=Raleigh,NC,US&appid={apiKey}" '. It would be easier if I showed you my code:
const request = require('request');
const express = require('express');
const HTTP_PORT = process.env.HTTP_PORT || 3001;
const app = express();
let bodyContent = null;
request.get("api.openweathermap.org/data/2.5/weather?q=Raleigh,NC,US&appid={apiKey}", function(err, res, body) {
if(!err && res.statusCode == 200) { // Successful response
console.log(body); // Displays the response from the API
bodyContent = body;
} else {
console.log(err);
bodyContent = err;
}
});
app.get("/weatherData", (req, res) => {
res.jsonp(bodyContent);
});
app.listen(HTTP_PORT, () => console.log(`Listening on port ${HTTP_PORT}`));
Note: I have hidden my api key for security reasons. My actual code replaces {apiKey} with my actual api key.
The documentation for this api says that the "api.openweathermap.org/..." URI is the proper way to make an api call. However, whenever I try to use this, nothing works.
Here is a link to the website so that you can see what I mean:
https://openweathermap.org/current#call

Here is my proposition, I added .dotenv package, and changed the code a little for this case.
const request = require("request");
const express = require("express");
const HTTP_PORT = process.env.HTTP_PORT || 3001;
require("dotenv").config();
const app = express();
let bodyContent = null;
request.get(
`${process.env.BASE_URL}weather?q=Raleigh,NC,US&appid=${process.env.API_KEY}`,
function (err, res, body) {
if (!err && res.statusCode == 200) {
// Successful response
console.log(body); // Displays the response from the API
bodyContent = body;
} else {
console.log(err);
bodyContent = err;
}
}
);
app.get("/weatherData", (req, res) => {
res.jsonp(bodyContent);
});
app.listen(HTTP_PORT, () => {
console.log(`Server is listening at http://localhost:${HTTP_PORT}`);
});
in VSCode:
.env file:
browser: http://localhost:3001/weatherData

Related

Node.js server return error 404 in production

hope you are good,
I am building my next.js weather app project using openweather API, I set up my proxy server, so the API key won't appear on the client side, it works perfect on my localhost, but when I deploy it on vercel or heroku, it returns error 404, it does the same when requesting directly on postman or browser.
PS: the environment variables are set in my vercel dashboard.
PS: api url example localhost:3000/api/weather?q=london
my server.js
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();
const needle = require('needle');
const url = require('url');
const cors = require('cors');
app.prepare().then(() => {
const API_BASE_URL = process.env.API_BASE_URL;
const API_KEY_NAME = process.env.API_KEY_NAME;
const API_KEY_VALUE = process.env.API_KEY_VALUE;
const server = express();
server.use(
cors({
origin: '*',
})
);
server.get(
'/api/:stat',
async (req, res) => {
try {
const params = new URLSearchParams({
...url.parse(req.url, true).slashes,
...url.parse(req.url, true).query,
[API_KEY_NAME]: API_KEY_VALUE,
});
const apiRes = await needle(
'get',
`${API_BASE_URL}/${req.params.stat}?${params}`
);
const data = apiRes.body;
res.status(200).json(data);
} catch (error) {
res.status(500).json({ error });
}
}
);
server.all('*', (req, res) => {
return handle(req, res);
});
server.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});

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

How to subscribe a HTTP endpoint to SNS in node js?

I am trying to subscribe my endpoint to a topic (I am using an EC2 instance), I have tried visiting my endpoint in a browser (GET request) to call sns.subscribe but I am not receiving a POST request afterwards.
The response I get from calling sns.subscribe is this.
{ ResponseMetadata: { RequestId: 'xxxx-xxxx-xxxx-xxx-xxxx' },
SubscriptionArn: 'arn:aws:sns:topic_location:xxxx:topic_name:xxxx-xxxx-xxxx-xxx-xxxx' }
This is my code.
const express = require("express");
const AWS = require('aws-sdk');
const request = require('request')
const bodyParser = require('body-parser')
const app = express();
var SNS_TOPIC_ARN = "arn:aws:sns:topic_location:xxxx:topic_name";
// configure AWS
AWS.config.update({
'accessKeyId': 'mykey',
'secretAccessKey': 'mysecretkey',
"region":"myregion"
});
const sns = new AWS.SNS();
app.get('/', (req, res) => {
var params = {
Protocol: 'http', /* required */ //http , https ,application
TopicArn: SNS_TOPIC_ARN, /* required */ // topic you want to subscribe
Endpoint: 'http://ec2-xx-xx-xx-xxx.myregion.compute.amazonaws.com/:80', // the endpoint that you want to receive notifications.
ReturnSubscriptionArn: true //|| false
};
sns.subscribe(params, function (err, data) {
if (err) {
console.log(err);
} else {
console.log(data);
}
});
res.end();
});
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.post('/', (req, res) => {
let body = ''
req.on('data', (chunk) => {
body += chunk.toString()
})
req.on('end', () => {
let payload = JSON.parse(body)
if (payload.Type === 'SubscriptionConfirmation') {
const promise = new Promise((resolve, reject) => {
const url = payload.SubscribeURL
request(url, (error, response) => {
if (!error && response.statusCode == 200) {
console.log('Yess! We have accepted the confirmation from AWS')
return resolve()
} else {
return reject()
}
})
})
promise.then(() => {
res.end("ok")
})
}
})
})
app.listen(80, process.env.IP, function(request, response){
console.log("## SERVER STARTED ##");
});
I had to remove my port number from the endpoint when calling sns.subscribe! My subscription has now been confirmed :D The new endpoint looks like this.
Endpoint: 'http://ec2-xx-xx-xx-xxx.myregion.compute.amazonaws.com/

Node: Is it possible that http server on request return the content from a request module?

What I want to do is to make a request using the "request" module when server receives a request, and return the content of that "request" back to the client. Is it possible?
const http = require("http");
const request = require("request");
const URL = "???";
const server = http.createServer();
server.on('request', (req, res) => {
// called once for every HTTP request
out_res = res;
make_request((err, res, body) => {
out_res.writeHead(200, {res});
out_res.write(body);
out_res.end();
});
});
function make_request(callback) {
request(URL, (err, res, body) => {
callback(err, res, body);
});
}
module.exports = () => {
server.listen(8080);
console.log('server start');
};
I got an error: ERR_STREAM_WRITE_AFTER_END, I've been a long time without node.js, but my friend asked me about some code and I just rewrite as above.
Ofcourse you can do that
server.on('request', (req, res) => {
request({uri: URL}).pipe(res);
});
Just pipe the response of API call to your router response object.
Here is how I would advise you to write your server code
var server = http.createServer(function(req,res){
if(req.url === '/' || req.url === '/index'){
request({uri: URL}).pipe(res);
}
.... //other conditions
});
server.listen(3000,'127.0.0.1')
Moreover, you can/should consider using express, it's really cool and easy to use to define routes etc

Node.js Application Performance

I currently have a node.js script sitting on Azure that gets a file (via a download URL link to that file) and base64 encodes it, and then sends this base64 encoded file back to the request source. The problem I am running into is performance based. The script below, in some instances, is timing out a separate application by having a run time over 30 seconds. The file in question on one of these timeouts was under a MB in size. Any ideas?
The script:
const express = require('express');
const bodyParser = require('body-parser');
const https = require('https');
const fs = require('fs');
const request = require('request');
const util = require('util');
const port = process.env.PORT || 3000;
var app = express();
app.use(bodyParser.json());
app.post('/base64file', (req, res) => {
var fileURL = req.body.fileURL;
var listenerToken = req.body.listenerToken;
var testingData = {
fileURL: fileURL,
listenerToken: listenerToken
};
/*
Make sure correct token is used to access endpoint..
*/
if( listenerToken !== <removedforprivacy> ) {
res.status(401);
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ error: 'You are not authorized'}));
} else if ( !fileURL ){
res.status(400);
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ error: 'The request could not be understood by the server due to malformed syntax.'}));
} else {
https.get(fileURL, function(response) {
var data = [];
response.on('data', function(chunk) {
data.push(chunk);
}).on('end', function() {
//build the base64 endoded file
var buffer = Buffer.concat(data).toString('base64');
//data to return
var returnData = {
base64File: buffer
};
if( buffer.length > 0 ) {
res.setHeader('Content-Type', 'application/json');
res.status(200);
res.send(JSON.stringify(returnData));
} else {
res.setHeader('Content-Type', 'application/json');
res.status(404);
res.send(JSON.stringify({ error: 'File URL not found.'}));
}
});
});
}
});
app.listen(port, () => {
console.log('Server is up and running ' + port);
});
One idea: you are missing error handling.
If you get an error on the https.get(), you will just never send a response and the original request will timeout.

Resources