Get the response headers from redirect url using node.js - node.js

Objective:
Te get the response.headers when I get the status code as 302 from redirects uri response
Issue:
I did a bit of googling about an issue which i'm facing at my end about the Redirect URL returning 500 rather than the expected 302. I found the npm request() can be used for redirects. However I'm not able to get the response headers as it always returns 500. But when I used the API end points manually with Postman (with interceptors turned ON) along with body and headers, I was able to get 302 redirects. This is essentially used for Automation testing for API
request(
url: 'https://blah/blah',
client_id:'something.com.au'
redirect_uri:'http://something' // used for mobile app and so it is OK to be have a valid url
response_type :'code'
scope : 'ALLAPI',
Username : 'cxxx'
Password : 'ccxcxc'
headers : {
'Content-Type': 'application/x-www-form-urlencoded',
'followRedirect' : true
}, function (error, response) {
console.log('The response val is', response.statusCode);
});
Question:
Not sure if npm request can do the justice or Am I using request in-correctly or should I have to use axios/follow-redirects etc.. something like that. Please advise. If anyone can provide proper directions on this, it'll be really helpful
Thanks,
Brad

I met the same problem, needle works for me.
var needle = require('needle'),
url = 'https://www.ibm.com/common/ssi/cgi-bin/ssialias?htmlfid=GBE03831USEN&';;
needle.get(url, {follow_max: 5}, function(error, res) {
console.log(res.statusCode);
});

#all. I've resolved using form property but with using req.post() method which returned the statuscode as 302 with response headers. Thanks all once again.

Related

How to modify a response in Electron

Let's say that I'm using a GET request on https://example.com and the response is this:
This is a response message.
How would I modify it in a way so that in my code, so that it can change the response to say something like this:
This is a MODIFIED response message.
For example, if my Electron app were to navigate to https://example.com, the screen would show me the modified content instead of the original content.
Essentially, I am trying to literally modify the request.
I have based my code off of this question but it only shows a proof of concept with a pre-typed Buffer, as in my situation I'd like modify the response instead of outright replacing it. So, my code looks like this:
protocol.interceptBufferProtocol("http", (req, CALLBACK) => {
if(req.url.includes("special url here")) {
var request = net.request({
method: req.method,
headers: req.headers,
url: req.url
});
request.on("response", (rp) => {
var d = [];
rp.on("data", c => d.push(c));
rp.on("end", () => {
var e = Buffer.concat(d);
console.log(e.toString());
// do SOMETHING with 'e', the response, then callback it.
CALLBACK(e);
});
});
request.end();
} else {
// Is supposedly going to carry out the request without interception
protocol.uninterceptProtocol("http");
}
}
This is supposed to manually request the URL, grab the response and return it. Without the protocol event, it works and gives me a response, but after some debugging, this piece of code consistently calls the same URL over and over with no response.
There is also the WebRequest API, but there is no way of modifying the response body, you can only modify the request headers & related content.
I haven't looked fully into Chromium-based solutions, but after looking at this, I'm not sure if it is possible to modify the response so it appears on my app's end in the first place. Additionally, I'm not familiar with the Chromium/Puppeteer messages that get sent all over the place.
Is there an elegant way to have Electron to get a URL response/request, call the URL using the headers/body/etc., then save & modify the response to appear different in Electron?

How do I use the the post method with fetch and koa?

This is a function on my front-end that makes the request.
function postNewUser(){
fetch(`http://12.0.0.1:8080/users/test`, {
method: 'POST',
body: {nome: name, email: "test#test.com.br", idade: 20}
})
}
This is my back-end code to receive the request.
router.post('/users/:id', koaBody(), ctx => {
ctx.set('Access-Control-Allow-Origin', '*');
users.push(ctx.request.body)
ctx.status = 201
ctx.body = ctx.params
console.log(users)
})
For some unknown reason I receive nothing. Not even a single error message. The "console.log()" on the back-end is also not triggered, so my theory is that the problem is on the front-end.
Edit
As sugested by gnososphere, I tested with Postman, and it worked. So now i know the problem must be on the fron-end code.
You can try your backend functionality with Postman. It's a great service for testing.
the request would look something like this
If the problem is on the frontend, double check your fetch method by posting to a website that will return data and logging that in your app.

use node.js send request for baidu map API get wrong response?

Im trying to use node.js to send http requst and call baidu map API.
my code in blow:
If you past the url and use browser directly, it will give right response in right format.
But when I use node to send request, I get problem.
var request = require('request');
request(
{ method: 'GET',
uri: 'http://api.map.baidu.com/place/v2/suggestion?query=beijing&region=131&output=json&ak=****hLQKu9ap9fPq5N1ExF1Kk7xe5Eah'
}
, function (error, response, body) {
res.json({
res:response
})
}
)
Meanwhile, if I change the url contains some Chinese like:
http://api.map.baidu.com/place/v2/suggestion?query=北京理工大学&region=北京&output=json&ak=****hLQKu9ap9fPq5N1ExF1Kk7xe5Eah
In node.js it will give status code 400 and totally wrong response.
you must encode your uri with encodeURI
uri: encodeURI('http://api.map.baidu.com/place/v2/suggestion?query=北京理工大学&region=北京&output=json&ak=3104hLQKu9ap9fPq5N1ExF1Kk7xe5Eah')

Mock a HEAD request for a redirect (via nock module)

In my project i try to expand tweets to be fully displayed. Links shorted by bit.ly are expanded by this peace of code (found # stackoverflow).
function expandUrl(shortUrl,callback) {
debug("expandUrl");
request( { method: "HEAD", url: shortUrl, followAllRedirects: true },
function (error, response) {
if (error) return callback(null,shortUrl);
return callback(null,response.request.href);
}
);
}
To have no need to be online during mocha tests, i would like to nock this part of code with the following:
nock('http://bit.ly')
.intercept("/1Ghc7dI","HEAD")
.reply(200,undefined,{location:"http://discoverspatial.com/courses/qgis-for-beginners"});
But this is not working. response.request.href is "undefined" after this job. (i tried href instead of location, this makes no difference.
To give a redirect you need to set the status to a HTTP URL redirection status as #apsillers says in the comments. Also if you don't want to be online, you need to nock the destination url as well, since request will call it to check that it's not a redirect:
nock('http://bit.ly')
.intercept("/1Ghc7dI","HEAD")
.reply(301,undefined,{location:"http://discoverspatial.com/courses/qgis-for-beginners"});
nock('http://discoverspatial.com')
.intercept("/courses/qgis-for-beginners", "HEAD")
.reply(200,"OK");

Setting request header in $.ajax

I need to make a request to a site which has HT Access enable. The str below has the username:password
Below is the code I am using
var str='msft:sks*';
var bytes = Crypto.charenc.Binary.stringToBytes(str);
var base64 = Crypto.util.bytesToBase64(bytes);
var auth='BASIC '+base64;
$.ajax({
url : 'http://mft.sta.com/',
method : 'GET',
async:false,
beforeSend : function(req,settings) {
req.setRequestHeader('Authorization', auth);
}
});
I am getting 401 authentication required error in FireBug.
But when i tried in POSTER plugin I am able to get the response. I copied the value of 'auth' in the above function and set it in the requester header for the key 'Authorization' in POSTER and it is working like a charm. But failing in Firefox or IE.
Any possible solution or workarounds.
Thanks in Advance.

Resources