Possible to remove User-agent header in supertest test? - supertest

I am trying to write some Supertest test cases where the User-Agent header is sent with a value, blank, or not at all.
I know I can use .set to handle setting a value for that header or '' for blank, but I am not sure how to omit the User-agent header completely. If I leave it off the request supertest sends a default value of node-superagent/1.2.0. If I .set('User-agent', null) it sends 'null' over the wire.
There doesn't appear to be a .remove or .delete. Anyone have an idea?
it ('example', function(done){
agent.post('/abc/a')
.set('User-agent', 'some agent')
.send('abc')
.expect(200)
.end(function(err, results){})
};

The method is called .unset(). You can use as follows:
it ('example', function(done){
agent.post('/abc/a')
.unset('User-Agent')
.send('abc')
.expect(200)
.end(function(err, results){})
};

Related

CSRF Token Name on Django Documentation is not Matching the Actual Name of the Variable in AJAX Header

I was struggling to send and recieve CSRF token, and I found, in the end, that Django was not able to get the token value because its name was different from the recommended one in its documentation. Why?
(I am doing AJAX on a HTTPS address and requests are cross-site.)
Django documentation recommends that I add token to AJAX header in following way:
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
Here, the name is X-CSRFToken, which somehow becomes HTTP_X_CSRFTOKEN.
On the other hand, Django is looking up the cookie under CSRF_COOKIE.
Line 278 in csrf.py of CsrfViewMiddleware:
csrf_token = request.META.get('CSRF_COOKIE')
if csrf_token is None:
# No CSRF cookie. For POST requests, we insist on a CSRF cookie,
# and in this way we can avoid all CSRF attacks, including login
# CSRF.
return self._reject(request, REASON_NO_CSRF_COOKIE)
I cannot change the variable name because I get this error:
Request header field CSRF_COOKIE is not allowed by Access-Control-Allow-Headers in preflight response.
So, I ended up changing the variable name in the source code from CSRF_COOKIE to HTTP_X_CSRFTOKEN. Are there any way to make this work?
(I do not do #csrf_exempt, so please do not recommend.)
The problem is not from Django, if you read closely here: https://docs.djangoproject.com/en/2.0/ref/csrf/#how-it-works you will understand how it works and what kind of logic they follow.
The problem is that you are not allowing the headers:
Request header field CSRF_COOKIE is not allowed by Access-Control-Allow-Headers in preflight response.
If you search for this ACAH you will find that you must edit your server config file to allow this kind of posts.
The other case is that you may not be sending properly the header and that's why it's looking for the cookie. In that case you can try adding this to your header:
xhr.setRequestHeader('X-CSRFToken': $('meta[name="token"]').attr('content') });

How to get value from header authorization bearer?

My server give response header authorization bearer.
How can I get this value in angular?
When you use $http, the third parameter of the promise callback contains the response headers. You should be able to get your header from there.
With the $http service you can receive the headers through the success functions response object. You can access this property through
$http(....).success(function(result, status, headers, config){
var myAuthHeader = headers("myAuthorizationHeader");
... Do something with your headers....
}
})

$routeProvider: templateUrl requests with X-Requested-With header

jQuery.ajax() normally sends an X-Requested-With header with XMLHttpRequest set as the content. On the server (in PHP), I usually detect this by testing:
$is_ajax = $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest'
In AngularJS, commonly found in $routeProvider.when(), you can obtain a template from the server with templateUrl: '/path/on/server'.
My problem is that templateUrl requests seem to not set X-Requested-With headers, so there's no way to distinguish templateUrl requests from any other type of request.
Is there any way to get $routeProvider to send X-Requested-With as XMLHttpRequest?
Reference:
$routeProvider Docs - (search templateUrl)
jQuery jqXHR - see jqXHR.setRequestHeader("X-Requested-With", "XMLHttpRequest")
Using Angular v1.1.5 via Google CDN
Update: I found the actual commit where Angular developers removed X-Requested-With from $http.get. Wonder why they would do that?
Update: https://github.com/angular/angular.js/issues/1004 - discussion where header was removed.
Tip of the hat to Zerot in FreeNode's #angularjs
app.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider) {
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$routeProvider.when('/', {
templateUrl: '/path/on/server',
controller: 'Ctrl'
});
});
Edit: to be more specific, this is the line you need somewhere:
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

Invalid JSON GET Request Express.js

While writing an API, I have come across a very thorny error: when I try to do a res.send(INSERT JSON) with a Content-Type header application/json (a default for most AJAX), I get an invalid json error. When I set the content-type to anything else (eg. text/plain), I get the correct response, but in order to use some front-end frameworks, I need to support application/json. Here is the actual error message:
Error: invalid json
at Object.exports.error (/Users/Brad/node_modules/express/node_modules/connect/lib/utils.js:44:13)
at IncomingMessage.module.exports (/Users/Brad/node_modules/express/node_modules/connect/lib/middleware/json.js:68:73)
at IncomingMessage.EventEmitter.emit (events.js:85:17)
at IncomingMessage._emitEnd (http.js:366:10)
at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23)
at Socket.socket.ondata (http.js:1680:22)
at TCP.onread (net.js:410:27)
My server code is below:
app.configure(function () {
app.use(express.bodyParser());
app.use(express.cookieParser('SALT'));
app.use(express.static(__dirname + '/static/'));
app.use(express.session());
});
app.get('/users', function(req, res) {
res.send({'test': 'test'});
});
Here is an picture of my Postman setup--I am using the Postman Chrome extension to test my API:
I believe the problem is that you want to be using Content-Type header in your servers response; not in your request Content-Type header.
When you use the Content-Type header in your request, Express will read the Content-Type and attempt to interpret the provided information as that Content-Type, in this case, as JSON. Because this is a GET request and thus has no body, Express is trying to interpret an empty string as JSON, which is giving you the error.

Get cookie from AJAX repsonse

I'm writing a chrome extension that uses AJAX to talk to a server. I want to read the KEY in set-cookie from AJAX response, but I cannot find a way to do this.
I have tried document.cookie and xhr.getAllResponseHeaders()
$.get(myURL,
function (output, status, xhr) {
console.log(document.cookie); //empty
console.log(xhr.getAllResponseHeaders());
//Only Connection and Content-Type shows
}
);
The raw response header is:
Connection:Close
Content-Type:text/html
Set-Cookie:KEY=DFDSFDCB; PATH=/;
I know that according to spec, getAllResponseHeaders() is supposed to filter out set-cookie field. Is there any workaround?

Resources