unable to fetch from api - node.js

const express = require("express");
const bodyParser = require("body-parser");
const request = require("request");
const app = express();
app.use(bodyParser.urlencoded({extended : true}));
app.listen(3000,function(){
console.log("server is running");
})
app.get("/",function(req,res){
res.sendFile(__dirname + "/index.html");
})
app.post("/",function(req,res){
var url = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?";
var pincode = req.body.pinCode;
url = url + "pincode=" + pincode;
var date = req.body.date;
url = url + "&date=" + date;
console.log(pincode,date);
request(url,function(err,res1,body){
res.send(body.centers);
})
})
for the above code (undefined) value is send in res.send(body.centers)
body is in json format given as below:
{"centers":[{"center_id":596215,"name":"MISSION UHC","address":"MISSION NADIAD","state_name":"Gujarat","district_name":"Kheda","block_name":"Nadiad","pincode":387002,"lat":22,"long":72,"from":"09:00:00","to":"18:00:00","fee_type":"Free"}

Try to see how body looks
request(url,function(err,res1,body) {
console.log(body);
})
If body output in terminal with double quote like :
{
"key": "value"
}
that's mean body is JSON string and you need to parsing it to object with :
body = JSON.parse(body)
Then send it :
res.send(body.centers)

Related

SyntaxError unexpected end of json input Node Js

I'm trying to retrieve data from Keepa using express js and HTTP module,
Keepa sending all data as gzip.
I was challenged to get the data properly and I got a previous error-Unexpected token in JSON at position 0,
So I have installed 'decompress-response' module which resolved this issue but now I'm getting half of the JSON data and then a new syntax error appears - unexpected end of json input Node Js
I'm trying to figure what am I missing here.. hope you can help me.
const express = require("express");
const https = require("https");
const decompressResponse = require("decompress-response");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res){
console.log(req.body.asinId);
const query = req.body.asinId;
const apiKey = "MY_API_KEY";
const url = "https://api.keepa.com/product?key="+ apiKey +"&domain=1&asin="+ query;
https.get(url, function(response){
response = decompressResponse(response);
console.log(response.statusCode);
console.log(response.headers);
var data;
response.on("data", function(chunk) {
if (!data) {
data = chunk;
} else {
data += chunk;
}
const asinData = JSON.parse(data);
console.log(asinData);
res.send();
});
});
});
Please try to print the response before "response = decompressResponse(response);". And let me know what you get there.

Unexpected token o in JSON - node / API

When ran, I get an error saying:
undefined:1
[object Object]
^
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse ()
the code:
const express = require("express");
const app = express();
const https = require("https");
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({extended: true}));
app.get("/",function (req,res) {
res.sendFile(__dirname + "/public/index.html")
app.use(express.static('public'));
})
app.post("/",function(req,res){
const firstName = req.body.firstName;
const lastName = req.body.lastName;
const email = req.body.email;
const data = {
members:{
email_address: email,
status:"subscribed",
merge_fields:{
FNAME:firstName,
LNAME:lastName
}
}
}
const jsonData = JSON.stringify(data);
const url = "https://us1.api.mailchimp.com/3.0/lists/";
const options = {
method:"POST",
auth:"sudolake:api_key"
}
const request = https.request(url, options, function(response){
response.on("data",function(){
console.log(JSON.parse(data));
})
})
request.write(jsonData);
request.end();
})
app.listen(3000, function(){
console.log("the server is up & running");
})
I know its probably something with the "const jsonData = JSON.stringify(data);" but I don't know what, its probably really stupid, thanks for any help

Unable to retrieve information from the Github API. JSON.parse() wont work in this code

Trying to retrieve information of any Github profile with the help of this API:
Github API - https://api.github.com/users/{username of any Github account}
const express = require("express");
const app = express();
const https = require("https");
const bodyParser = require("body-parser");
const request = require("request");
app.listen(3000 , function(){
console.log("Server started at port 3000");
});
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended:true}));
app.get("/" , function(req , res){
res.sendFile(__dirname +"/index.html" );
});
app.post("/" , function(req , res){
const user = req.body.username;
const url = "https://api.github.com/users/"+user ;
https.get(url , function(response){
response.on("data", function(data){
const temp = JSON.parse(data);
const bravo = temp.login;
res.write("<p>The login of this Github ID is " + bravo + "<p>" );
});
});
console.log("Post request received.");
});
Getting error in my CLI stating user agent error and unexpected token R in JSON at position 2
The target of your requests won't return in json format if there is a space or other invalid character in the uri you call.
calling with "testme" as your bravo variable rendered json but "testme please" returned html.
I think if you log data before trying to parse it as json you will find you're being served html.

I did not get to receive post data in json

From javascript on the client side I send 3 variables per ajax post, and on the server I try to view the json content of the client and it shows me undefined, I do not know where the problem is, I attach the code (refactored):
file : ./routes/index.js
'use strict'
const express = require('express')
const user_controller = require('../controller/user')
const api = express.Router()
// pagina de Inicio
api.get('/index',function(req,res){
res.render('index')
})
// Gestion de usuarios
api.get('/usuarios',user_controller.getAllUsers)
api.post('/usuarios',user_controller.newUser)
api.get('/usuario',user_controller.getUser)
api.post('/logear',user_controller.logear)
api.post('/registrar',user_controller.registrar)
module.exports = api
file : ./controller/user.js
function registrar(req,res){
var bcrypt = require('bcrypt');
var BCRYPT_SALT_ROUNDS = 12;
var user = req.body.user;
var email = req.body.email;
var pass = req.body.pass;
console.log('info: ' + user + ' ' + email + ' ' +pass);
//console.log('perro: ' + req.body);
// encriptamos la contraseƱa
bcrypt.genSalt(10, function(err, salt) {
if(error) throw error;
else{
bcrypt.hash(pass, BCRYPT_SALT_ROUNDS, function(err, hash) {
pass = hash;
});
}
});
//bcrypt.hash(pass, BCRYPT_SALT_ROUNDS).then(function(hashedPassword) {pass = hashedPassword});
conexion_db.query({ ... etc
file: ./app.js
'use strict'
//configuracion del servidor
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.set('view engine','jade');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
const api = require('./routes');
app.use('/api',api);
module.exports = app
file: client.js
$.ajax({
url: 'http://localhost:3000/api/registrar',
data: JSON.stringify({'user': $('#nick').val(),'email': $('#email').val(),'pass': $('#pass').val()}),
type: "POST",
dataType: 'json',
success: function(json) {
console.log("json: " + json.estado);
console.log("json: " + json.user);
console.log("json: " + json.pass);
I get on cmd server, this: info: undefined undefined undefined
The bodyParser middleware can not handle the json data because you have not set the ContentType.jQuery ajax default value of contentType parameter is "application/x-www-form-urlencoded; charset=UTF-8".But you are sending data in json type.You need to set ContentType to application/json.
You can also give PlainObject to the data parameter.

Start a proxy server with nodejs so that it serves requests preprended with "/wps_proxy/wps_proxy?url="

I want to start a proxy server with node.js so that it serves requests preprended with "/wps_proxy/wps_proxy?url=". I want it so I can use the wps-js library of north52 (check the installation tips) . I have already a server where I run my application.
What I did try until now is :
the server.js file
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var path = require("path");
var app = express();
app.use(express.static(__dirname + '/' + 'public'));
var urlencodedParser = bodyParser.urlencoded({ extended: false });
//****** this is my try ******************************
app.get('/wps_proxy/wps_proxy',function (req,res){
res.sendfile(__dirname + '/' + 'public/wps_proxy/wps-js/target/wps-js-0.1.2-SNAPSHOT/example.html');
if(req.query !== undefined){//because it enters sometimes without url
var http = require('http');
//Options to be used by request
var options = {
host:"geostatistics.demo.52north.org",//fixed given data
port:"80",
path:"/wps/WebProcessingService"
};
var callback = function(response){
var dat = "";
response.on("data",function(data){
dat+=data;
});
response.on("end", function(){
res.end(dat)
})
};
//Make the request
var req = http.request(options,callback);
req.end()
}
})
var ipaddress = process.env.OPENSHIFT_NODEJS_IP||'127.0.0.1';
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
app.set('port', port);
app.listen(app.get('port'),ipaddress, function() {
console.log( 'Server started on port ' + app.get('port'))
})
//***************************************
but its not working.. I think that the data are not sent back correctly..
This is a live example of what I want to do.. http://geoprocessing.demo.52north.org/wps-js-0.1.1/
and this is a live example of my application (check the console for errors) http://gws-hydris.rhcloud.com/wps_proxy/wps_proxy
I did find my answer from this post How to create a simple http proxy in node.js? so the way i solve it was:
app.get('/wps_proxy/wps_proxy',function (req,res){
var queryData = url.parse(req.url, true).query;
if (queryData.url) {
request({
url: queryData.url
}).on('error', function(e) {
res.end(e);
}).pipe(res);
}
else {
res.end("no url found");
}
})

Resources