EzDevInfo.com

superagent

Ajax with less suck - (and node.js HTTP client to match) SuperAgent - Ajax with less suck

Encoding issue with superagent

I am trying to perform an API call with superagent but it encodes my api key which gets rejected.

get(url).query({ key: 'Fmjtd%7Cluu').end(function(err, res) {

The key is being sent as

Fmjtd%257Cluu

Any ideas how to prevent this using superagent? If I make it part of the 'url' part it's fine but I would like to pass it as query data if possible.


Source: (StackOverflow)

How to get rid of supertest's output when testing express applications?

I'm building an Express.js API and I'm using mocha and supertest for testing.

However, take a look at this:

  root path
GET / 200 5.789 ms - 19
    ✓ returns 200 status code 
GET / 200 0.787 ms - 19
    ✓ returns json mime type 
GET / 200 0.382 ms - 19
    ✓ contains the package version

I want to get rid of the GET / 200 log so it can look like this:

  root path
    ✓ returns 200 status code
    ✓ returns json mime type
    ✓ contains the package version

Any ideas?


Source: (StackOverflow)

Advertisements

Streaming data events aren't registered

I'm using superagent to receive a notifications stream from a server

require('superagent')
  .post('www.streaming.example.com')
  .type('application/json')
  .send({ foo: 'bar' })
  .on('data', function(chunk) {
    console.log('chunk:' + chunk); // nothing shows up
  })
  .on('readable', function() {
    console.log('new data in!');   // nothing shows up
  })
  .pipe(process.stdout);           // data is on the screen

For some reason data and readable events aren't registered, hovewer I can pipe data to the sceeen. How can I process data on the fly?


Source: (StackOverflow)

How do I prevent SuperAgent AJAX from calling OPTIONS?

I found the source of my problem for SuperAgent (http://visionmedia.github.com/superagent/) on Firefox. Not sure if SuperAgent is doing it in its AJAX call or if FireFox is triggering it.

Essentially, every time I make an AJAX call an OPTIONS method is being fired on the URL before the actual AJAX call. Quite annoying since the server currently doesn't support OPTIONS. How can I make a call without it going to crap and re-coding the server?

Thanks


Source: (StackOverflow)

How can you use cookies with superagent?

I'm doing cookie session management with express with something like this:

req.session.authentication = auth;

And I verify the authenticated urls with something like

if(!req.session.authentication){res.send(401);}

Now I'm building tests for the URLs with mocha, superagent and should, however I can't seem to find a way to get/set the cookie with superagent. I even tried to request the login before the authenticated test but it is not working,

I have tried adding the request to the login in the before statement for the mocha BDD suite, however it is still telling me that the request is unauthorized, I have tested the authentication doing the requests from the browser, however it is not working from the suite any ideas why?


Source: (StackOverflow)

Superagent 'request' object is being redefined as function?

I'm trying to put together a supertest-based integration test suite (run by Mocha) that pings our REST API and validates the response.

However, my test doesn't seem to be running as expected:

var assert = require('assert')
var should = require('should')
var request = require('superagent')

var WEBSERVICE_BASE = 'localhost:8080/our-application/'

describe('Authentication', function() {
  it('prevents user from logging in without credentials', function() {
    console.log('###')
    console.log('Starting with: ' + request)
    console.log('###')
    request.get(WEBSERVICE_BASE + 'auth', function(err, res) {
      console.log('Error: ' + err)
      if (err) {
        throw err
      }
      res.should.have.status(401)
      done()
    })
  })
})

What I see in the console:

Craigs-MBP:mocha-tests Craig$ ./run.sh


  Authentication
###
Starting with: function request(method, url) {
  // callback
  if ('function' == typeof url) {
    return new Request('GET', method).end(url);
  }

  // url first
  if (1 == arguments.length) {
    return new Request('GET', method);
  }

  return new Request(method, url);
}
###
    ✓ prevents user from logging in without credentials

    1 passing (12ms)

It seems request is being redefined as a function, instead of the superagent object?

The test should not pass, and at the very least the console.log printing the err parameter should be seen.


Source: (StackOverflow)

Mocha Test: Uncaught TypeError: Cannot read property 'status' of null

Learning TDD and my first simple test for my "Hello World" server response is failing in Mocha. I'm using Mocha.js, Superagent, & Expect.js.

When I curl -i localhost:8080, I get the correct response and status code.

HTTP/1.1 200 OK
Content-Type: text/plain
Date: Mon, 27 Apr 2015 17:55:36 GMT
Connection: keep-alive
Transfer-Encoding: chunked

Hello World

Test code:

var request = require('superagent');
var expect = require('expect.js');

// Test structure
describe('Suite one', function(){
    it("should get a response that contains World",function(done){
        request.get('localhost:8080').end(function(res){
            // TODO check that response is okay
            expect(res).to.exist;
            expect(res.status).to.equal(200);
            expect(res.body).to.contain('World');
            done();
        });
    });
});

Server code:

var server = require('http').createServer(function(req, res){
    res.writeHead(200, {"Content-Type":"text/plain"});
    res.end('Hello World\n');
});

server.listen(8080, function(){
    console.log("Server listening at port 8080");
});

Mocha output:

  Suite one
    1) should get a response that contains World


  0 passing (110ms)
  1 failing

  1) Suite one should get a response that contains World:
     Uncaught TypeError: Cannot read property 'status' of null
      at test.js:10:23
      at _stream_readable.js:908:16

I've tried googling this issue but no luck finding out what I'm doing wrong.


Source: (StackOverflow)

".use" method to add logic on each request of SuperAgent

This issue in SuperAgent repository mentions the .use method to add logic on each request. For example, adding an Authorization header for JWT when a token is available:

superagent.use( bearer );

function bearer ( request ) {
    var token = sessionStorage.get( 'token' );

    if ( token ) request.set( 'Authorization', 'Bearer ' + token );
}

Although the last comment informs that this feature is working again, I can't make it to work.

The following test code:

var request = require( 'superagent' );

request.use( bearer );

function bearer ( request )
{
    // "config" is a global var where token and other stuff resides
    if ( config.token ) request.set( 'Authorization', 'Bearer ' + config.token );
}

Returns this error:

request.use( bearer );
        ^
TypeError: undefined is not a function

Edit for the downvoter: Why, Mr Anderson? Why... Why?


Source: (StackOverflow)

How can I inject a custom HTTP Header into every request that SuperAgent makes?

Clearly SuperAgent supports custom HTTP headers:

request
   .post('/api/pet')
   .send({ name: 'Manny', species: 'cat' })
   .set('X-API-Key', 'foobar')
   .set('Accept', 'application/json')
   .end(function(err, res){
     if (res.ok) {
       alert('yay got ' + JSON.stringify(res.body));
     } else {
       alert('Oh no! error ' + res.text);
     }
   });

My Question:

  • If I'm pulling down SuperAgent via npm, how can I inject my own HTTP header across all requests that SuperAgent makes?
  • Note: I'm entire willing to create a new npm package that extends SuperAgent if necessary.

Source: (StackOverflow)

Promises es6 and superagent

I'm attempting to use es6 promises with superagent. I'm attempting to call a function that has a superagent request wrapped inside.

Request.post(buildReq).then(res => {
 if (res.ok) {//process res}
});

Here is the function wrapping superagent

  static post(params) {
    superagent
      .post(params.url)
      .send(params.payload)
      .set('Accept', 'application/json')
      .end((error, res) => {
        return this.Promise.resolve(res);
      })
      .bind(this);
  }

I'm getting an error

enter code here Uncaught TypeError: Cannot read property 'then' of undefined

When I change the return of the function to

static post(params) {
    return Promise.resolve(superagent
      .post(params.url)
      .auth(params.auth.username, params.auth.password)
      .send(params.payload)
      .set('Accept', 'application/json')
      .end((error, res) => {
        return this.Promise.resolve(res);
      })
    );
  }

It looks like the data is returned in my browser's dev tools, but I cannot get to it within the .then function. How can I get the response from the promise.


Source: (StackOverflow)

IE XHR: jQuery.ajax vs TJ's superagent

I noticed TJ Holowaychuk's superagent library ("Ajax with less suck") try's several ActiveXObject methods for IE when generating a cross browser XHR object:

// ...if normal browser:
  return new XMLHttpRequest;
} else {
  try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
  try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
  try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
  try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
}

The full code: https://github.com/visionmedia/superagent/blob/master/build/build.js#L359-376

In jQuery, this is not attempted, and I'm curious what's going on here.

You can search jQuery source for 'ActiveXObject' and see for yourself: http://code.jquery.com/jquery-1.8.2.js

When does new ActiveXObject('Microsoft.XMLHTTP'); throw and waterfall down to the other options?


Source: (StackOverflow)

How can i test from mocha/superagent a CORS upload call to amazon-s3?

I am having problems trying to do a CORS request from superagent to Amazon S3 for upload a file. First, I am asking to a node.js server for the policy. I return a JSON object like this:

{
    s3PolicyBase64: '',
    s3Signature: '',
    s3Key: '',
    s3ObjectKey: 'ftriana3185/inputData/input_fdc2f7f4b050c5884e5ac60a43bfc0d8ff26d549.csv' }

Then I try from superagent use the policy returned by node to upload a local file. My code looks like this:

it('GET /inputFiles/s3Credential', function(done) {
    var csvPath = './files/inputFileResource/countrylist.csv';
    var request = {};
    request.ext = 'csv';

    clientAgent.get(localPath + '/inputFiles/s3Credential').send(request).end(function(response) {
        var s3PolicyBase64 = response.body.s3PolicyBase64;
        var s3Signature = response.body.s3Signature;
        var s3Key = response.body.s3Key;
        var s3ObjectKey = response.body.s3ObjectKey;

        var request = clientAgent.post('bucket-name.s3.amazonaws.com')
            .type('form')
            .field('key', s3ObjectKey)
            .field('AWSAccessKeyId', s3Key)
            .field('acl', 'public-read')
            .field('policy', s3PolicyBase64)
            .field('signature', s3Signature)
            .attach('mycsv', csvPath).end(function(response){
                console.log(response);
            });
    });
});

I am sure that the problem is in the form that i am doing the request from superagent because i also have a html form that works fine. So, what is the correct form to use superagent for this purpose?


Source: (StackOverflow)

SuperAgent + Node.js Connection Refused

I'm pretty new to Node.js so this is possibly an basic understanding issue, but I'm getting ECONNREFUSED from a superagent http request when I don't think I should be:

$ curl http://localhost:5000/
{"you": "looking good"}

$ node
> var request = require("superagent");
> var req = request.get("http://localhost:5000/").on('error', function (err) {
    console.log("There's an emergency is going on.", err)
  }).end(function (data) {
    console.log("All is well", data.body)
  });

There's an emergency is going on. { [Error: connect ECONNREFUSED]
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect' }

What assumption have I made that is breaking this? I'm actually writing isomorphic JavaScript and the exact same code making the http query on the browser works fine!


Source: (StackOverflow)

Superagent: PUT-ing multipart form data

Is it possible to do a PUT request with multipart form data?

With Superagent I would expect the following to work, but it doesn't.

var request = Request
  .put("http://localhost:8080/upload_file")
  .field("name", file.name)
  .field("size", file.size)
  .attach("file", file.file, file.file.name)
  .accept("application/json")

If I do a post, it works. The difference is the Content-Type. With the successful post request the Content-Type is multipart/form-data; boundary=------WebKitFormBoundaryXg34NkBFcYWq60mH.

If I were to set this manually how would I know what the boundary should be? It seems to be automatically generated by Superagent.


Source: (StackOverflow)

How do I send a request with superagent that uses the same query parameter

I am trying to make a request against a php server that is constructing the url like this:

website.com/?q=help&q=moreHelp&q=evenMoreHelp

How do I use superagent to pass the same query with multiple values?

I've tried this:

req.get('website.com').query({q:'help',q:'moreHelp',q:'evenMoreHelp'}).end(...)

But I'm not sure it is actually sending all three 'q' values. What am I supposed to do to make sure they all get sent?


Source: (StackOverflow)