### Make a GET Request Source: https://github.com/forwardemail/superagent/blob/master/index.html Example of making a GET request to retrieve user data. ```javascript request.get('/user') .accept('json') ``` -------------------------------- ### Simple GET Request with Callback Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html A basic example of making a GET request and handling the response using a callback function. It asserts that the response object is valid and contains text content. ```javascript request('GET', `${uri}/ok`).end((error, res) => { try { assert(res instanceof request.Response, 'respond with Response'); assert(res.ok, 'response should be ok'); assert(res.text, 'res.text'); next(); } catch (err) { next(err); } }); ``` -------------------------------- ### Simple GET Request using .get() Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html A concise way to make a GET request using the `.get()` method. This example initiates the request and expects an error, likely due to the endpoint not existing or returning an error. ```javascript request.get(`${uri}/notfound`).end((error, res) => { try { assert(error); ``` -------------------------------- ### Make a GET Request Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Demonstrates making a GET request and asserting that no default user-agent header is set. ```javascript request.get(`${base}/ua`).then((res) => { assert(res.headers); assert(!res.headers['user-agent']); }) ``` -------------------------------- ### request.get Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Demonstrates making a GET request using SuperAgent. This example shows how to handle responses and errors, and how to pipe a read stream to the request. ```APIDOC ## request.get ### Description Initiates an HTTP GET request. ### Method GET ### Endpoint [Full endpoint path with any path parameters] ### Request Example ```javascript const request_ = request.get(base + '/badRedirectNoLocation'); request_.type('json'); request_.on('response', (res) => { responseCalled = true; }); request_.on('error', (error) => { error.message.should.eql('No location header for redirect'); errorCalled = true; stream.end(); }); ``` ### Response #### Success Response (200) - **body** (object) - The response body. #### Error Response - **error** (object) - An error object if the request fails, e.g., due to bad redirects. ``` -------------------------------- ### Simple GET Request with Callback Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Demonstrates a basic GET request and handling the response within a callback. Asserts that the response is an instance of request.Response and that it is 'ok'. ```javascript request('GET', `${uri}/ok`).end((error, res) => { try { assert(res instanceof request.Response, 'respond with Response'); assert(res.ok, 'response should be ok'); assert(res.text, 'res.text'); next(); } catch (err) { next(err); } }); ``` -------------------------------- ### Set Host Header with request.get().set() Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html This example shows how to set the 'host' header for a GET request using `.set()`. It also demonstrates using `.connect()` for host mapping. ```javascript app.get('/', (request_, res) => { assert.equal(request_.hostname, 'example.com'); res.end(); }); server = http.createServer(app); server.listen(0, function listening() { request .get(`http://localhost:${server.address().port}`) .set('host', 'example.com') .then(() => { return request .get(`http://example.com:${server.address().port}`) .connect({ 'example.com': 'localhost', '*': 'fail' }); }) .then(() => done(), done); }); ``` -------------------------------- ### Handle GET Request for 404 Not Found Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Specific example for handling a 404 Not Found error. Asserts that an error occurred and checks for the presence of the `.notFound` property on the response. ```javascript request('GET', `${uri}/notfound`).end((error, res) => { try { assert(error); assert(res.notFound, 'response should be .notFound'); next(); } catch (err) { next(err); } }); ``` -------------------------------- ### get() Method Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Demonstrates using the shorthand .get() method for making a GET request. Asserts that an error occurred and verifies the response status and statusType. ```javascript request.get(`${uri}/notfound`).end((error, res) => { try { assert(error); assert.equal(404, res.status, 'response .status'); assert.equal(4, res.statusType, 'response .statusType'); next(); } catch (err) { next(err); } }); ``` -------------------------------- ### Query String Construction (GET) Source: https://github.com/forwardemail/superagent/blob/master/docs/index.md Demonstrates how to build query strings for GET requests using the `.query()` method. ```APIDOC ## Query String Construction (GET) ### Description The `.query()` method can be used to construct query strings for GET requests. It accepts objects or strings. ### Method GET ### Endpoint /search ### Parameters #### Query Parameters - **query** (string) - The search term. - **range** (string) - The range for the search. - **order** (string) - The order of results. ### Request Example ```javascript request .get('/search') .query({ query: 'Manny', range: '1..5', order: 'desc' }) .then(res => { }); ``` ``` -------------------------------- ### Request with Callback and Shorthand Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Demonstrates making a GET request using the shorthand method with a callback. ```javascript request.get(`${uri}/login`, (error, res) => { assert.equal(res.status, 200); done(); }); ``` -------------------------------- ### Request with URL and Callback Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Initiate a GET request by providing the URL and a callback function to handle the response. ```javascript request(`${uri}/foo`, (error, res) => { try { assert.equal('bar', res.body.foo); next(); } catch (err) { next(err); } }); ``` -------------------------------- ### GET request with callback and Accept header Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Perform a GET request, set the 'Accept' header, and handle the response in a callback. Asserts that the response text matches the 'Accept' header value. ```javascript request .get(`${uri}/echo-header/accept`) .set('Accept', 'foo/bar') .end((error, res) => { try { assert.equal('foo/bar', res.text); next(); } catch (err) { next(err); } }); ``` -------------------------------- ### Set Request Timeout Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html This example shows how to set a timeout for a GET request using the `.timeout()` method. It then asserts the error details if the timeout is exceeded. ```javascript const request_ = request.get(`${uri}/delay/const`).timeout(1000); request_.end((error, res) => { try { assert(error, 'error missing'); assert.equal(1000, error.timeout, 'err.timeout missing'); assert.equal( 'Timeout of 1000ms exceeded', error.message, 'err.message incorrect' ); assert.equal(null, res); assert(request_.timedout, true); next(); } catch (err) { next(err); } }); ``` -------------------------------- ### request .get() with no data or callback Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Example of making a GET request without providing data or a callback function. ```APIDOC ## GET /echo-header/content-type ### Description Makes a GET request to an endpoint that echoes the 'content-type' header, without specifying data or a callback. ### Method GET ### Endpoint /echo-header/content-type ``` -------------------------------- ### Default GET Method Source: https://github.com/forwardemail/superagent/blob/master/docs/index.md Shows that the GET method is the default if no method is specified. ```APIDOC ## Default GET Method ### Description If no HTTP method is explicitly specified, SuperAgent defaults to using the GET method. ### Method GET (default) ### Endpoint /search ### Request Example ```javascript request('/search', (err, res) => { }); ``` ``` -------------------------------- ### Make a POST Request Source: https://github.com/forwardemail/superagent/blob/master/index.html Example of making a POST request, with the content type specified as PNG. ```javascript request.post('/user') .accept('png') ``` -------------------------------- ### Query String Construction with Strings (GET) Source: https://github.com/forwardemail/superagent/blob/master/docs/index.md Shows how to build query strings for GET requests using string arguments with `.query()`. ```APIDOC ## Query String Construction with Strings (GET) ### Description The `.query()` method can also accept raw query strings or build them incrementally. ### Method GET ### Endpoint /querystring ### Parameters #### Query Parameters - **search** (string) - The search term. - **range** (string) - The range for the search. ### Request Example ```javascript request .get('/querystring') .query('search=Manny&range=1..5') .then(res => { }); ``` ``` -------------------------------- ### Serialize Request to JSON Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html This example shows how to use the `.toJSON()` method on a request to get a JSON representation of its properties, asserting the presence of common fields. ```javascript request.get(`${uri}/ok`).end((error, res) => { try { const index = (res.request || res.req).toJSON(); for (const property of ['url', 'method', 'data', 'headers']) { assert(index.hasOwnProperty(property)); } next(); } catch (err) { next(err); } }); ``` -------------------------------- ### Basic GET Request Source: https://github.com/forwardemail/superagent/blob/master/docs/index.md Initiates a GET request and handles the response or errors using Promises. ```APIDOC ## GET /search ### Description Initiates a GET request to the /search endpoint and handles the response using Promises. ### Method GET ### Endpoint /search ### Response #### Success Response (200) - **res.body** (any) - The response body. - **res.headers** (object) - The response headers. - **res.status** (number) - The HTTP status code. ### Response Example ```json { "example": "response body" } ``` ### Error Handling #### Error Response - **err.message** (string) - The error message. - **err.response** (object) - The error response object. ``` -------------------------------- ### HTTPS Request to Root Path with CA (Unix Sockets) Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html This example makes an HTTPS GET request to the root path ('/') using Unix sockets, providing a CA certificate. It asserts that there are no errors and the response is OK. ```javascript request .get(`${base}/`) .ca(cacert) .end((error, res) => { assert.ifError(error); assert(res.ok); assert.strictEqual('root ok!', res.text); done(); }); ``` -------------------------------- ### Handle Response Event Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html This example shows how to listen for the 'response' event to access the response object and assert a property of its body. ```javascript request .get(`${uri}/foo`) .on('response', (res) => { try { assert.equal('bar', res.body.foo); next(); } catch (err) { next(err); } }) .end(); ``` -------------------------------- ### Browser Support: Browserslist Output Source: https://github.com/forwardemail/superagent/blob/master/README.md Example output from the browserslist command, indicating the range of browsers targeted by Superagent. ```text and_chr 102 and_ff 101 and_qq 10.4 and_uc 12.12 android 101 chrome 103 chrome 102 chrome 101 chrome 100 edge 103 edge 102 edge 101 firefox 101 firefox 100 firefox 91 ios_saf 15.5 ios_saf 15.4 ios_saf 15.2-15.3 ios_saf 15.0-15.1 ios_saf 14.5-14.8 ios_saf 14.0-14.4 ios_saf 12.2-12.5 kaios 2.5 op_mini all op_mob 64 opera 86 opera 85 safari 15.5 safari 15.4 samsung 17.0 samsung 16.0 ``` -------------------------------- ### Request with Callback Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Shows how to make a GET request and handle the response using a callback function, asserting the status code. ```javascript request.get(`${uri}/login`, (error, res) => { try { assert.strictEqual(res.statusCode, 200); done(); } catch (err) { done(err); } }); ``` -------------------------------- ### Simple GET Request without Callback Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Illustrates making a simple GET request without providing an explicit callback function. The request will be initiated, but response handling is omitted. ```javascript request('GET', 'test/test.request.js').end(); next(); ``` -------------------------------- ### Basic GET Request Source: https://github.com/forwardemail/superagent/blob/master/index.html Initiates a GET request and handles the response using Promises. Includes basic error handling. ```APIDOC ## GET /search ### Description Sends a GET request to the /search endpoint and processes the response or errors using Promises. ### Method GET ### Endpoint /search ### Parameters None explicitly documented for this basic example. ### Request Example ```javascript request .get('/search') .then(res => { // res.body, res.headers, res.status }) .catch(err => { // err.message, err.response }); ``` ### Response #### Success Response (200) - **res.body**: The response body. - **res.headers**: The response headers. - **res.status**: The HTTP status code. #### Response Example ```json { "example": "response body" } ``` #### Error Response - **err.message**: The error message. - **err.response**: The response object associated with the error. ``` -------------------------------- ### Query String Parameters for GET Source: https://github.com/forwardemail/superagent/blob/master/index.html Demonstrates how to append query string parameters to a GET request using the `.query()` method. ```APIDOC ## GET /search with Query Parameters ### Description Appends query string parameters to a GET request. The `.query()` method can be used multiple times or with an object. ### Method GET ### Endpoint /search ### Parameters #### Query Parameters - **query** (string) - The search query. - **range** (string) - The range for the search. - **order** (string) - The order of results. ### Request Example ```javascript // Appending multiple query parameters request .get('/search') .query({ query: 'Manny' }) .query({ range: '1..5' }) .query({ order: 'desc' }) .then(res => { // Handle response }); // Appending query parameters as a single object request .get('/search') .query({ query: 'Manny', range: '1..5', order: 'desc' }) .then(res => { // Handle response }); // Using string for query parameters request .get('/querystring') .query('search=Manny&range=1..5') .then(res => { // Handle response }); ``` ### Response Standard success and error responses apply. ``` -------------------------------- ### Accepting HTML Content Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Use the .accept() method to specify the desired content type for the response. This example demonstrates accepting 'text/html'. ```javascript request .get(`${uri}/echo`) .accept('html') .end((error, res) => { try { res.header.accept.should.equal('text/html'); done(); } catch (err) { done(err); } }); ``` -------------------------------- ### Install Superagent with npm Source: https://github.com/forwardemail/superagent/blob/master/README.md Use npm to add Superagent to your project dependencies. ```sh npm install superagent ``` -------------------------------- ### Default GET Request with Callback Source: https://github.com/forwardemail/superagent/blob/master/index.html When no HTTP method is specified, SuperAgent defaults to GET. This example shows a request with a callback function. ```javascript request('/search', (err, res) => { }); ``` -------------------------------- ### GET request with accept() for application/xml Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Use `.accept('application/xml')` to explicitly request the 'application/xml' content type. Asserts that the response text is 'application/xml'. ```javascript request .get(`${uri}/echo-header/accept`) .accept('application/xml') .end((error, res) => { try { assert.equal('application/xml', res.text); next(); } catch (err) { next(err); } }); ``` -------------------------------- ### Persistent Agent: Start with Empty Session Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Checks if a persistent agent starts with an empty session. A GET request should result in a 401 status and a 'set-cookie' header. ```javascript agent1.get(`${base}/dashboard`).end((error, res) => { should.exist(error); res.should.have.status(401); should.exist(res.headers['set-cookie']); done(); }); ``` -------------------------------- ### Follow redirects with GET requests Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html SuperAgent automatically follows redirects for GET requests. This example demonstrates following 301, 302, 303, and 307 redirects. ```javascript const request_ = request.get(`${base}/test-301`).redirects(1); request_.end((error, res) => { const headers = request_.req.getHeaders ? request_.req.getHeaders() : request_.req._headers; headers.host.should.eql(`localhost:${server2.address().port}`); res.status.should.eql(200); res.text.should.eql('GET'); done(); }); ``` ```javascript const request_ = request.get(`${base}/test-302`).redirects(1); request_.end((error, res) => { const headers = request_.req.getHeaders ? request_.req.getHeaders() : request_.req._headers; res.status.should.eql(200); res.text.should.eql('GET'); done(); }); ``` ```javascript const request_ = request.get(`${base}/test-303`).redirects(1); request_.end((error, res) => { const headers = request_.req.getHeaders ? request_.req.getHeaders() : request_.req._headers; headers.host.should.eql(`localhost:${server2.address().port}`); res.status.should.eql(200); res.text.should.eql('GET'); done(); }); ``` ```javascript const request_ = request.get(`${base}/test-307`).redirects(1); request_.end((error, res) => { const headers = request_.req.getHeaders ? request_.req.getHeaders() : request_.req._headers; ``` -------------------------------- ### Node.js Usage: POST Request with Async/Await Source: https://github.com/forwardemail/superagent/blob/master/README.md Example of making a POST request in Node.js using async/await syntax for handling promises. ```js (async () => { try { const res = await superagent.post('/api/pet'); console.log(res); } catch (err) { console.error(err); } })(); ``` -------------------------------- ### Conditional GET Request (Not Modified) Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html This example shows how to perform a GET request and check for a 200 status, then use the `If-Modified-Since` header in a subsequent request to receive a 304 status if the resource has not changed. ```javascript request.get(`${base}/if-mod`).end((error, res) => { res.should.have.status(200); res.text.should.match(/^\d+$/); ts = Number(res.text); done(); }); ``` ```javascript request .get(`${base}/if-mod`) .set('If-Modified-Since', new Date(ts).toUTCString()) .end((error, res) => { res.should.have.status(304); // res.text.should.be.empty done(); }); ``` -------------------------------- ### req.timeout(ms) with redirect Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html This example demonstrates setting a timeout on a request that involves a redirect. The timeout still applies to the initial request. ```javascript const request_ = request.get(`${uri}/delay/const`).timeout(1000); request_.end((error, res) => { try { assert(error, 'error missing'); assert.equal(1000, error.timeout, 'err.timeout missing'); assert.equal( 'Timeout of 1000ms exceeded', error.message, 'err.message incorrect' ); assert.equal(null, res); assert(request_.timedout, true); next(); } catch (err) { next(err); } }); ``` -------------------------------- ### Install Superagent with yarn Source: https://github.com/forwardemail/superagent/blob/master/README.md Use yarn to add Superagent to your project dependencies. ```sh yarn add superagent ``` -------------------------------- ### Agent Defaults Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Demonstrates how an agent remembers default settings like accept headers, query parameters, and custom headers across multiple requests. ```javascript if (typeof Promise === 'undefined') { return; } let called = 0; let event_called = 0; const agent = request .agent() .accept('json') .use(() => { called++; }) .once('request', () => { event_called++; }) .query({ hello: 'world' }) .set('X-test', 'testing'); assert.equal(0, called); assert.equal(0, event_called); return agent .get(`${base}/echo`) .then((res) => { assert.equal(1, called); assert.equal(1, event_called); assert.equal('application/json', res.headers.accept); assert.equal('testing', res.headers['x-test']); return agent.get(`${base}/querystring`); }) .then((res) => { assert.equal(2, called); assert.equal(2, event_called); assert.deepEqual({ hello: 'world' }, res.body); }); ``` -------------------------------- ### HTTPS Request to /request/path via Unix Socket Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Example of making an HTTPS GET request to '/request/path' using a Unix socket. ```javascript request .get(`${base}/request/path`) ``` -------------------------------- ### Basic Auth with Credentials in URL Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Demonstrates setting basic authentication credentials directly within the URL. ```javascript const new_url = URL.parse(base); new_url.auth = 'tobi:learnboost'; new_url.pathname = '/basic-auth'; request.get(URL.format(new_url)).end((error, res) => { res.status.should.equal(200); done(); }); ``` -------------------------------- ### Simple HEAD Request Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Shows how to perform a HEAD request and verify the response. Asserts that the response is an instance of request.Response and that it is 'ok', but has no text content. ```javascript request.head(`${uri}/ok`).end((error, res) => { try { assert(res instanceof request.Response, 'respond with Response'); assert(res.ok, 'response should be ok'); assert(!res.text, 'res.text'); next(); } catch (err) { next(err); } }); ``` -------------------------------- ### request(url, fn) Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Initiates a GET request to the URL and provides a callback function to handle the response. ```APIDOC ## Request by URL and Callback ### Description Sends a GET request to the specified URL and executes a callback function upon completion. ### Method GET ### Endpoint [URL specified] ### Parameters #### Callback Function - **error** - An error object if the request failed. - **res** - The response object. ### Request Example ```javascript request('/foo', (error, res) => { // Handle response }); ``` ### Response #### Success Response (200) - **foo** (string) - Expected value 'bar'. #### Response Example ```json { "foo": "bar" } ``` ``` -------------------------------- ### Handle GET Request for 401 Unauthorized Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Example for handling a 401 Unauthorized error. Asserts that an error occurred and checks for the `.unauthorized` property on the response. ```javascript request('GET', `${uri}/unauthorized`).end((error, res) => { try { assert(error); assert(res.unauthorized, 'response should be .unauthorized'); next(); } catch (err) { next(err); } }); ``` -------------------------------- ### Basic Auth with req.auth(user, pass) Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Shows how to use the `.auth(user, pass)` method to set basic authentication credentials for a request. ```javascript request .get(`${base}/basic-auth`) .auth('tobi', 'learnboost') .end((error, res) => { res.status.should.equal(200); done(); }); ``` -------------------------------- ### GET Request with Query String Strings Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Add query parameters by passing raw string arguments to multiple .query() calls. ```javascript request .get(`${uri}/querystring`) .query('search=Manny') .query('range=1..5') .query('order=desc') .end((error, res) => { try { assert.deepEqual(res.body, { search: 'Manny', range: '1..5', order: 'desc' }); next(); } catch (err) { next(err); } }); ``` -------------------------------- ### HTTPS Request to Root Path via Unix Socket Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Example of making an HTTPS GET request to the root path ('/') using a Unix socket, including certificate handling. ```javascript request .get(`${base}/`) .ca(cacert) .end((error, res) => { assert.ifError(error); assert(res.ok); assert.strictEqual('root ok!', res.text); done(); }); ``` -------------------------------- ### Process Response as Readable Stream Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html This example shows how to treat a response as a readable stream. It demonstrates listening for 'end' and 'close' events, and using pause, resume, and destroy methods. ```javascript const request_ = request.get(base).buffer(false); request_.end((error, res) => { if (error) return done(error); let trackEndEvent = 0; let trackCloseEvent = 0; res.on('end', () => { trackEndEvent++; trackEndEvent.should.equal(1); if (!process.env.HTTP2_TEST) { trackCloseEvent.should.equal(0); // close should not have been called } done(); }); res.on('close', () => { trackCloseEvent++; }); setTimeout(() => { (() => { res.pause(); }).should.not.throw(); (() => { res.resume(); }).should.not.throw(); (() => { res.destroy(); }).should.not.throw(); }, 50); }); ``` -------------------------------- ### Set Agent with http.Agent Instance Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Shows how to set a custom http.Agent instance for a request and verifies that the agent is correctly applied. ```javascript const http = require('http'); const request_ = request.get(`${base}/echo`); const agent = new http.Agent(); const returnValue = request_.agent(agent); returnValue.should.equal(request_); request_.agent().should.equal(agent); done(); ``` -------------------------------- ### get() Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html A shorthand method for making GET requests, verifying the response status and status type. ```APIDOC ## GET /notfound ### Description Uses the `get()` shorthand to make a GET request and verify response status properties. ### Method GET ### Endpoint /notfound ### Response #### Success Response (404) - **status** (number) - The HTTP status code of the response. - **statusType** (number) - A numerical representation of the status code type. ``` -------------------------------- ### Follow Location with IP Override Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Demonstrates following redirects with a specific IP address override for the connection. Ensure the 'connect' method is used correctly with the desired IP. ```javascript const redirects = []; const url = URL.parse(base); return request .get(`http://redir.example.com:${url.port || '80'}${url.pathname}`) .connect({ '*': url.hostname }) .on('redirect', (res) => { redirects.push(res.headers.location); }) .then((res) => { const array = ['/movies', '/movies/all', '/movies/all/0']; redirects.should.eql(array); res.text.should.equal('first movie page'); }); ``` -------------------------------- ### request() GET 204 No Content Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Illustrates a GET request to an endpoint that returns a 204 No Content status. ```APIDOC ## GET /no-content ### Description Makes a GET request to an endpoint that should return a 204 No Content status. ### Method GET ### Endpoint /no-content ### Response #### Success Response (204) - **noContent** (boolean) - Indicates if the response has no content. ``` -------------------------------- ### GET Request to Check Response Charset Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Make a GET request and assert that the response 'charset' is 'utf-8'. ```javascript request.get(`${uri}/text`).end((error, res) => { try { assert.equal('utf-8', res.charset); next(); } catch (err) { next(err); } }); ``` -------------------------------- ### Agents for Global State (Cookies & Defaults) Source: https://github.com/forwardemail/superagent/blob/master/docs/index.md Explains how to use `.agent()` to create isolated cookie jars and set default options for multiple requests. ```APIDOC ## Agents for global state ### Saving cookies In Node SuperAgent does not save cookies by default, but you can use the `.agent()` method to create a copy of SuperAgent that saves cookies. Each copy has a separate cookie jar. ```javascript const agent = request.agent(); agent .post('/login') .then(() => { return agent.get('/cookied-page'); }); ``` In browsers cookies are managed automatically by the browser, so the `.agent()` does not isolate cookies. ### Default options for multiple requests Regular request methods called on the agent will be used as defaults for all requests made by that agent. ```javascript const agent = request.agent() .use(plugin) .auth(shared); await agent.get('/with-plugin-and-auth'); await agent.get('/also-with-plugin-and-auth'); ``` The complete list of methods that the agent can use to set defaults is: `use`, `on`, `once`, `set`, `query`, `type`, `accept`, `auth`, `withCredentials`, `sortQuery`, `retry`, `ok`, `redirects`, `timeout`, `buffer`, `serialize`, `parse`, `ca`, `key`, `pfx`, `cert`. ``` -------------------------------- ### Browser Support: Browserslist Configuration Source: https://github.com/forwardemail/superagent/blob/master/README.md Displays the supported browser versions as defined by the browserslist configuration. ```sh npx browserslist ``` -------------------------------- ### GET Request to Check Response Type Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Make a GET request and assert that the response 'type' is 'application/json'. ```javascript request.get(`${uri}/pets`).end((error, res) => { try { assert.equal('application/json', res.type); next(); } catch (err) { next(err); } }); ``` -------------------------------- ### GET shorthand payload goes to querystring Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Shows how a shorthand payload in a GET request is automatically appended to the querystring. ```APIDOC ## GET /querystring (Shorthand) ### Description Sends a GET request where the second argument is treated as query parameters. ### Method GET ### Endpoint /querystring ### Parameters #### Query Parameters - **foo** (string) - Required - The value for foo. - **bar** (string) - Required - The value for bar. ### Request Example ```javascript request.get( '/querystring', { foo: 'FOO', bar: 'BAR' }, (error, res) => { // Handle response } ); ``` ### Response #### Success Response (200) - **foo** (string) - The value of foo. - **bar** (string) - The value of bar. #### Response Example ```json { "foo": "FOO", "bar": "BAR" } ``` ``` -------------------------------- ### request() GET 406 Not Acceptable Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Shows how to make a GET request to an endpoint that should result in a 406 Not Acceptable status. ```APIDOC ## GET /not-acceptable ### Description Makes a GET request to an endpoint that should return a 406 Not Acceptable status. ### Method GET ### Endpoint /not-acceptable ### Response #### Success Response (406) - **notAcceptable** (boolean) - Indicates if the response is not acceptable. ``` -------------------------------- ### GET Request with Single Query Object Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Perform a GET request with a single key-value pair in the query string. ```javascript request .get(`${uri}/querystring`) .query({ search: 'Manny' }) .end((error, res) => { try { assert.deepEqual(res.body, { search: 'Manny' }); next(); } catch (err) { next(err); } }); ``` -------------------------------- ### POST Request with Data and Callback Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Shows how to send data with a POST request and handle the response using a callback. ```javascript request.post(`${uri}/echo`, { foo: 'bar' }, (error, res) => { assert.equal('{"foo":"bar"}', res.text); done(); }); ``` -------------------------------- ### GET Request with Two Query Object Arrays Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Include two separate arrays as query parameters in a GET request. ```javascript request .get(`${uri}/querystring`) .query({ array1: ['a', 'b', 'c'], array2: [1, 2, 3] }) .end((error, res) => { try { assert.deepEqual(res.body, { array1: ['a', 'b', 'c'], array2: [1, 2, 3] }); next(); } catch (err) { next(err); } }); ``` -------------------------------- ### Follow Redirects on HEAD When Configured Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Demonstrates enabling redirects for HEAD requests by setting the `redirects` option. This allows the request to follow a specified number of redirects. ```javascript const redirects = []; request .head(base) .redirects(10) .on('redirect', (res) => { redirects.push(res.headers.location); }) .end((error, res) => { try { const array = []; array.push('/movies', '/movies/all', '/movies/all/0'); redirects.should.eql(array); assert(!res.text); done(); } catch (err) { done(err); } }); ``` -------------------------------- ### GET Request with Query Object Array Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Make a GET request and pass an array as a query parameter using an object. ```javascript request .get(`${uri}/querystring`) .query({ val: ['a', 'b', 'c'] }) .end((error, res) => { try { assert.deepEqual(res.body, { val: ['a', 'b', 'c'] }); next(); } catch (err) { next(err); } }); ``` -------------------------------- ### post() Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Illustrates making a POST request and asserting the response text. ```APIDOC ## POST /user ### Description Makes a POST request to create a user resource and asserts the response text. ### Method POST ### Endpoint /user ### Response #### Success Response - **text** (string) - The text content of the response, expected to be 'created'. ``` -------------------------------- ### Attach Multiple Files Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Demonstrates attaching multiple files with different names and verifies that the server correctly receives and processes each file, including its original filename, mimetype, and content. ```javascript const request_ = request.post(`${base}/echo`); request_.attach('one', 'test/node/fixtures/user.html'); request_.attach('two', 'test/node/fixtures/user.json'); request_.attach('three', 'test/node/fixtures/user.txt'); return request_.then((res) => { const html = res.files.one; const json = res.files.two; const text = res.files.three; html.originalFilename.should.equal('user.html'); html.mimetype.should.equal('text/html'); read(html.filepath).should.equal('

name

'); json.originalFilename.should.equal('user.json'); json.mimetype.should.equal('application/json'); read(json.filepath).should.equal('{"name":"tobi"}'); text.originalFilename.should.equal('user.txt'); text.mimetype.should.equal('text/plain'); read(text.filepath).should.equal('Tobi'); }); ``` -------------------------------- ### GET Request with 307 Redirect Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Tests if a GET request correctly follows a 307 redirect and verifies the host and response text. ```javascript const request_ = request.get(`${base}/test-307`).redirects(1); request_.end((error, res) => { const headers = request_.req.getHeaders ? request_.req.getHeaders() : request_.req._headers; headers.host.should.eql(`localhost:${server2.address().port}`); res.status.should.eql(200); res.text.should.eql('GET'); done(); }); ``` -------------------------------- ### Set Accept to XML Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Using `.accept('xml')` sets the `Accept` header to `application/xml`. ```javascript request .get(`${uri}/echo`) .accept('xml') .end((error, res) => { try { // Mime module keeps changing this :( assert( res.header.accept == 'application/xml' || ``` -------------------------------- ### GET Request with 303 Redirect Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Tests if a GET request correctly follows a 303 redirect and verifies the host and response text. ```javascript const request_ = request.get(`${base}/test-303`).redirects(1); request_.end((error, res) => { const headers = request_.req.getHeaders ? request_.req.getHeaders() : request_.req._headers; headers.host.should.eql(`localhost:${server2.address().port}`); res.status.should.eql(200); res.text.should.eql('GET'); done(); }); ``` -------------------------------- ### request .accept() with json Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Illustrates setting the 'Accept' header to 'json' and verifying the response. ```APIDOC ## GET /echo-header/accept ### Description Makes a GET request, sets the 'Accept' header to 'json', and asserts the response text. ### Method GET ### Endpoint /echo-header/accept ### Headers - **Accept** (string) - Set to 'json'. ### Response #### Success Response - **text** (string) - The text content of the response, expected to be 'application/json'. ``` -------------------------------- ### HTTP Request to Root Path (Unix Sockets) Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Demonstrates making a GET request to the root path ('/') using Unix sockets. Asserts that the response is OK and the text content is 'root ok!'. ```javascript request.get(`${base}/`).end((error, res) => { assert(res.ok); assert.strictEqual('root ok!', res.text); done(); }); ``` -------------------------------- ### GET Request with 302 Redirect Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Tests if a GET request correctly follows a 302 redirect and verifies the response status and text. ```javascript const request_ = request.get(`${base}/test-302`).redirects(1); request_.end((error, res) => { const headers = request_.req.getHeaders ? request_.req.getHeaders() : request_.req._headers; res.status.should.eql(200); res.text.should.eql('GET'); done(); }); ``` -------------------------------- ### Follow Redirects and Capture Location Headers Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Shows how to listen for the 'redirect' event to capture the location headers during a series of redirects. Verifies that the captured locations match the expected sequence. ```javascript const redirects = []; request .get(base) .on('redirect', (res) => { redirects.push(res.headers.location); }) .end((error, res) => { try { const array = ['/movies', '/movies/all', '/movies/all/0']; redirects.should.eql(array); ``` -------------------------------- ### GET Request with 301 Redirect Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Tests if a GET request correctly follows a 301 redirect and verifies the host and response text. ```javascript const request_ = request.get(`${base}/test-301`).redirects(1); request_.end((error, res) => { const headers = request_.req.getHeaders ? request_.req.getHeaders() : request_.req._headers; headers.host.should.eql(`localhost:${server2.address().port}`); res.status.should.eql(200); res.text.should.eql('GET'); done(); }); ``` -------------------------------- ### GET querystring with strings and objects Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Demonstrates how to append query string parameters to a GET request, supporting both string and object formats. ```APIDOC ## GET /querystring ### Description Sends a GET request to the /querystring endpoint with query parameters. ### Method GET ### Endpoint /querystring ### Parameters #### Query Parameters - **search** (string) - Required - The search term. - **order** (string) - Required - The order direction (e.g., 'desc'). - **range** (string) - Required - The range for the query (e.g., '1..5'). ### Request Example ```javascript request .get('/querystring') .query('search=Manny') .query({ order: 'desc', range: '1..5' }) .end((error, res) => { // Handle response }); ``` ### Response #### Success Response (200) - **search** (string) - The search term. - **range** (string) - The range specified. - **order** (string) - The order direction. #### Response Example ```json { "search": "Manny", "range": "1..5", "order": "desc" } ``` ``` -------------------------------- ### request .accept() with application/json Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Demonstrates setting the 'Accept' header to the full MIME type 'application/json'. ```APIDOC ## GET /echo-header/accept ### Description Makes a GET request, sets the 'Accept' header to 'application/json', and asserts the response text. ### Method GET ### Endpoint /echo-header/accept ### Headers - **Accept** (string) - Set to 'application/json'. ### Response #### Success Response - **text** (string) - The text content of the response, expected to be 'application/json'. ``` -------------------------------- ### request() GET 401 Bad Request Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Demonstrates making a GET request to an unauthorized endpoint and asserting the error and unauthorized status. ```APIDOC ## GET /unauthorized ### Description Makes a GET request to an endpoint that should return a 401 Unauthorized status. ### Method GET ### Endpoint /unauthorized ### Response #### Success Response (401) - **unauthorized** (boolean) - Indicates if the response is unauthorized. ``` -------------------------------- ### Support Setting Individual Timeout Options Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Demonstrates setting individual timeout options like deadline and response timeout. Checks for the expected error code and errno. ```javascript request .get(`${base}/delay/500`) .timeout({ deadline: 10 }) .timeout({ response: 99_999 }) .end((error, res) => { assert(error, 'expected an error'); assert.equal('ECONNABORTED', error.code, 'expected abort error code'); assert.equal('ETIME', error.errno); done(); }); ``` -------------------------------- ### GET Request for Binary Data Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Make a GET request for binary data. The '.buffer()' method is used to accumulate the response body. ```javascript request .get(`${uri}/binary-data`) .buffer() .end((error, res) => { try { assert.ifError(error); assert.deepEqual(res.body, binData); next(); } catch (err) { next(err); } }); ``` -------------------------------- ### Setting Accept Header Source: https://github.com/forwardemail/superagent/blob/master/docs/index.md Demonstrates how to specify the desired response content type using the `.accept()` method. ```APIDOC ## Setting Accept Header ### Description Specifies the desired 'Accept' header for the response using the `.accept()` method. ### Method GET ### Endpoint /user ### Request Example (MIME Type) ```javascript request.get('/user') .accept('application/json') ``` ### Request Example (Extension) ```javascript request.get('/user') .accept('json') ``` ### Request Example (POST with Accept) ```javascript request.post('/user') .accept('png') ``` ``` -------------------------------- ### GET Request for JSON Response Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Make a GET request and assert that the parsed JSON response body matches the expected array. ```javascript request.get(`${uri}/pets`).end((error, res) => { try { assert.deepEqual(res.body, ['tobi', 'loki', 'jane']); next(); } catch (err) { next(err); } }); ``` -------------------------------- ### Basic Auth with req.auth(user:pass) Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Demonstrates using `.auth(user)` when the password is concatenated with the username in the argument. ```javascript request .get(`${base}/basic-auth/again`) .auth('tobi') .end((error, res) => { res.status.should.eql(200); done(); }); ``` -------------------------------- ### GET request without callback Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Perform a GET request without providing a callback function. The request is initiated, and `next()` is called. ```javascript request.get(`${uri}/echo-header/content-type`); next(); ``` -------------------------------- ### Handling POST Redirects Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Shows how to send a POST request and handle subsequent redirects, verifying the redirect chain. ```javascript agent1 .post(`${base}/redirect`) .send({ foo: 'bar', baz: 'blaaah' }) .then((res) => { res.should.have.status(200); res.text.should.containEql('simple'); res.redirects.should.eql([`${base}/simple`]); }) ``` -------------------------------- ### Query String Construction (HEAD) Source: https://github.com/forwardemail/superagent/blob/master/docs/index.md Demonstrates using the `.query()` method for HEAD requests. ```APIDOC ## Query String Construction (HEAD) ### Description The `.query()` method can be used with HEAD requests to specify query parameters. ### Method HEAD ### Endpoint /users ### Parameters #### Query Parameters - **email** (string) - The email address to query. ### Request Example ```javascript request .head('/users') .query({ email: 'joe@smith.com' }) .then(res => { }); ``` ``` -------------------------------- ### GET querystring with strings and objects Source: https://github.com/forwardemail/superagent/blob/master/docs/test.html Use the .query() method to append query string parameters to a GET request. It accepts both strings and objects. ```javascript request .get(`${uri}/querystring`) .query('search=Manny') .query({ order: 'desc', range: '1..5' }) .end((error, res) => { try { assert.deepEqual(res.body, { search: 'Manny', range: '1..5', order: 'desc' }); next(); } catch (err) { next(err); } }); ```