JSON Request works in Javascript but not in Nodejs (statusCode: 403) - javascript

I want to request a simple JSON File in NodeJS. With Javascript and jQuery it works like a charm:
$(document).ready(function() {
$.getJSON('https://www.younow.com/php/api/broadcast/info/curId=0/user=Peter', function(json) {
if (json["errorCode"] > 0) {
console.log("Offline");
$('#ampel').addClass('red');
} else {
console.log("Online");
$('#ampel').addClass('green');
}
});
})
But i can't get it to work with NodeJS:
var request = require('request');
var options = {
url: 'https://www.younow.com/php/api/broadcast/info/curId=0/user=Peter',
headers: {
'content-type': 'application/javascript'
}
};
function callback(error, response, body) {
console.log(response.statusCode);
}
request(options, callback);
The StatusCode is always 403 and i can't work with the data. Can somebody help me, so i can get the same result like with jQuery?
Thanks!

I was able to find the solution with Mike McCaughan's help:
I had to send a different user-agent to get a 200 response. The code looks like this now:
var options = {
url: 'https://www.younow.com/php/api/broadcast/info/curId=0/user=',
headers: {
'User-Agent': 'request'
}
};
function callback(error, response, body) {
var str = JSON.parse(body);
if (str.errorCode > 0) {
...
} else {
...
}
}
request(options, callback);

Related

Request Params Node JS 500 Error

As the uri is generated is as expected and list data is shown in page but while sending the req in request method, 500 error occurs instead of retruning body.
uri: http://yufluyuinnepal.com/?vTRIPTYPE=O&vOPSID=O&vSTRFROM=KTM&vSTRFROMTXT=&vSTRTO=PKR&vSTRTOTXT=&vFLIGHTDATE=27-Nov-2018&vRETURNDATE=27-Nov-2018&vADULT=1&vCHILD=0&vNATIONALITY=NP&vNATIONALITYTXT=Nepal&
const uri = `http://yufluyuinnepal.com/?${queryString(query)}`;
console.log(uri);
const req = {
uri: uri,
};
request(req, (error, response, body) => {
if (error) {
return reject(error);
}
if (response.statusCode !== 200) {
return reject(new Error(`Expected 200 but got ${response.statusCode}`));
}
return resolve(body);
});
Let me know how can i return body and what is wrong in my code.
In Request npm module, specify what kind of request is it (GET/POST etc)
// Example GET Request
var options = {
method: "GET",
url:
uri,
headers:
{
// headers as per documentation
}
};
request(options, (error, response, body) => {
if(error){}
if(response.statusCode !== 200){}
return resolve(body);
})
This is your current implementation with a callback function.
const req = {
uri: uri,
method: 'GET'/'POST'
};
request(req, (error, response, body) => {
if (error) {
console.log(error);
}
if (response.statusCode !== 200) {
//Do something
}
console.log(body);
//Do something
});
When using request-promise module you should write something like this
var rp = require('request-promise');
const req = {
uri: uri,
method: 'GET'/'POST'
}
rp(req)
.then((res) => {
//Do something
})
.catch((error) => {
//Do something with error
});
Please try this
let requestp=require('request-promise');
var options = {
    method: 'POST',
    url: 'uri',
    resolveWithFullResponse: true,
    headers: {
                'Accept': 'application/json',
                'Content-Type' : 'application/json'
            },
            body: TextedValue
        };
     
        await  requestp(options).then(async function(Content){
           await requestp(options).then(async function(response){
                if (await response.statusCode == 200)
                    {
                        console.log(Content); // in ur case it is body
                    }
                 else
                    {
                        console.log("Response code "+response.statusCode+" .Try Again Later")
                   }
                })
           })

Purging Cloudflare cache with an API call in Node.js

I'm looking to purge Cloudflare's cache through its API. More specially, the purge all files command.
However, I keep running into the "Invalid Content-Type header, valid values are application/json,multipart/form-data" error message, despite explicitly setting the Content-Type header with Node.js' request package.
What am I missing?
var request = require('request');
gulp.task('cfPurge', function() {
var options = {
url: 'https://api.cloudflare.com/client/v4/zones/myZoneID/purge_cache',
headers: {
'X-Auth-Email': 'email',
'X-Auth-Key': 'myAPIkey',
'Content-Type': 'application/json'
},
form: {
'purge_everything': true,
}
};
function callback(error, response, body) {
var resp = JSON.parse(body);
if (!error & response.statusCode == 200) {
console.log('CF Purge: ', resp.success);
}
else {
console.log('Error: ', resp.errors);
for (var i = 0; i < resp.errors.length; i++)
console.log(' ', resp.errors[i]);
console.log('Message: ', resp.messages);
console.log('Result: ', resp.result);
}
}
return request.post(options, callback);
});
Output:
Error: [ { code: 6003,
message: 'Invalid request headers',
error_chain: [ [Object] ] } ]
{ code: 6003,
message: 'Invalid request headers',
error_chain:
[ { code: 6105,
message: 'Invalid Content-Type header, valid values are application/json,multipart/form-data' } ] }
Message: []
Result: null
According to the documentation for the cloudfare API, you need to send an HTTP DELETE request and not an HTTP POST request:
Modify the line...
return request.post(options, callback);
...with:
return request.del(options, callback);
Also, this is not a form. You need to put the JSON in the body of the data. So, replace the block...
form: {
'purge_everything': true,
}
...with:
body: JSON.stringify({'purge_everything': true})

Node / Javascript - pipe writeStream / file to post request

I have the following code, it creates a file on a remote server from a test var (just to make sure it worked), but now I need to upload a file and I'm not sure how to actually attach it to the request, here is the code:
var dataString = '#test.txt';
var options = {
uri: 'https://site.zendesk.com/api/v2/uploads.json?filename=test.txt',
method: 'POST',
headers: {
'Content-Type': 'application/binary',
'Accept': 'application/json',
Authorization: 'Basic bXVydGV6LmF....'
},
body: dataString
//this will create a test file with some text, but I need
//to upload a file on my machine instead
}
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
var x = {
error: error,
response: response,
body: body
}
console.log(x);
}
request(options, callback);
I was thinking something in the lines of:
fs.createReadStream('text.txt').pipe({function?})
But I'm not sure how to finish this part unfortunately.
update: 2019
It's been a LONG time, but someone asked for the solution. I'm not sure if this is how I fixed it tbh or if this code even works, but I found this digging around, give it a try.
Also, Zendesk updated their API at some point, not sure when exactly so this may be old anyways:
var uploadAttachment = function() {
var uOptions = {
uri: 'xxx/api/v2/uploads.json?filename=' + fileName,
method: 'POST',
headers: {
'Content-Type': 'application/binary',
'Accept': 'application/json',
Authorization: 'Basic xxx'
}
};
function callback(error, response, body) {
if (!body) {
if (error) {
return next(error);
} else {
var x = {
error: true,
message: "Some message",
err: response
};
return next(x);
}
}
if (body && body.error) {
return next(error);
}
if (error) {
return next(error);
}
var jr = JSON.parse(body);
var uploaded = {};
if (jr.upload) {
uploaded = jr.upload;
}
attachToComment(uploaded);
}
fs.createReadStream(tempPath + fileName).pipe(request(uOptions, callback));
};
I hope this helps, sorry in advance if it does not work, I no longer have access to zendesk.

How to make a GET and POST request to an external API?

var Attendance = require('../../../collections/attendance').Attendance;
var moment = require('moment');
module.exports = function(app) {
app.get('/api/trackmyclass/attendance', function(req, res) {
var data = req.body;
data['user'] = req.user;
Attendance.getByUser(data, function(err, d) {
if (err) {
console.log('This is the err' + err.message);
res.json(err, 400);
} else {
var job = d['attendance'];
if (typeof job != undefined) {
res.json(job);
console.log('This is it' + job['status']);
} else
res.json('No data Present', 200);
}
});
});
app.post('/api/trackmyclass/attendance', function(req, res) {
var data = req.body;
data['user'] = req.user;
Attendance.create(data, function(err, d) {
if (err) {
console.log('This is the err' + err.message);
res.json(err, 400);
} else {
var attendance = d['attendance'];
if (typeof job != undefined) {
console.log('Attendance record created' + attendance);
res.json(attendance);
} else
res.json('No data Present', 200);
}
});
});
}
This is the api code I to which I need to make the GET and POST request. But I have no idea how to do it.
It looks like your code is using express which would normally be good for building and API for your app. However to make a simple request to a third party api and staying in node.js why not try the request module which is great. https://www.npmjs.org/package/request
Your example does not show what the path of the request is or if you need any additinal headers etc but here is a simple example of a GET request using request.
var request = require('request');
function makeCall (callback) {
// here we make a call using request module
request.get(
{ uri: 'THEPATHAND ENDPOINT YOU REQUEST,
json: true,
headers: {
'Content-Type' : 'application/x-www-form-urlencoded',
}
},
function (error, res, object) {
if (error) { return callback(error); }
if (res.statusCode != 200 ) {
return callback('statusCode');
}
callback(null, object);
}
);
}
or jquery .ajax from a front end client direcct to your path
$.ajax({
url: "pathtoyourdata",
type: "GET",
})
.done(function (data) {
//stuff with your data
});

catch response when send jsonp request phonegap

I write application by phonegap
Server Side I write by nodejs
exports.login = function(request, response) {
var keys = Object.keys(request.query);
request.body= JSON.parse(keys[1]);
Accounts.findOne({
name : request.body.name
}, function(err, docs) {
if (!docs) {
response.json('{"error": "user-not-found"}');
} else {
console.log("docs: ", docs);
Accounts.validatePassword(request.body.password, docs['hashedPass'], docs['salt'], function(error, res) {
if (error) {
response.json(error);
}
if (res) {
generateToken(request.body.name, request.body.device, function(res) {
if (res) {
response.json('{"token": "' + res + '"}');
} else {
response.json('{"error": "cant-create-token"}');
}
});
} else {
response.json('{"error": "invalid-password"}');
}
});
}
})
}
Phonegap: I write function to login
function LoginUser(info)
{
var varUrl=server+"/auth/login";
$.ajax({
url:varUrl,
type:"GET",
contentType:"application/json",
headers: {
Accept:"application/json",
"Access-Control-Allow-Origin": "*"
},
data:info,
dataType:"jsonp",
success:function(data)
{
console.log("HERE");
console.log(data);
},
error: function(err){
console.log(err);
}
});
}
and I request it will like this http://localhost:3000/auth/login?callback=jQuery161014894121675752103_1361459462241&{%22name%22:%22fdfdfd%22,%22password%22:%22fdfdfdfd%22}&_=1361459615743
and when I see in the response of tab network of developer of chrome is "{\"error\": \"user-not-found\"}"
but I can not catch this repsonse in function LoginUser(info) above
How to get it because in console it print error: function(err){
console.log(err);
}
I dont know why.
Can you help me.
On the server side you have to use callback and in the response of your
jsonp file you need to do:
jQuery161014894121675752103_1361459462241({"error": "user-not-found"})
Where the function name comes from the callback variable in your jsonp request.
Cause a jsonp request just "include" a script tag in your site, which can execute js (basically).

Categories

Resources