jshttp / accepts Goto Github PK
View Code? Open in Web Editor NEWHigher-level content negotiation
License: MIT License
Higher-level content negotiation
License: MIT License
When a user gives an unknown file extension to types, it crashes with TypeError: Object false has no method 'match'
when it didn't use to.
As per spec https://www.rfc-editor.org/rfc/rfc9110#section-12.5.1-14 this is valid:
Accept: text/*, text/plain, text/plain;format=flowed, */*
This library does not seem to have a way to extract the format parameter, does it?
Would that be something the lib should support or is that out of scope and should be a separate package?
A header like this application/json; charset=utf-8
Works correctly with accept.types()
=> [ 'application/json' ])
But accept.type(['text', 'application/json']
or accept.type(['text', 'json']
gives false
It seems to be a problem here:
https://github.com/jshttp/negotiator/blob/master/lib/mediaType.js#L141
Since we then compare the keys and our accepted type application/json
does not have the charset key.
I'm trying to use this in Koa.js and the results are indeterministic.
For example
// "normal" browser request (Chrome)
// accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
this.request.accept.types('json'); // -> 'json'
this.request.accept.types('html'); // -> 'html'
// ajax ($.getJSON) request with jQuery (Chrome)
// accept: application/json, text/javascript, */*; q=0.01
this.request.accept.types('json'); // -> 'json'
this.request.accept.types('html'); // -> 'html'
there should be a strict mode, or something. How can the program determine accurately what response type to return?
Hello again :)
In lots of places in my app I have this line
if (req.accepts('json') && !req.accepts('html')) {
// process the GET request from superagent (client)
...
res.json(200, data);
} else {
// middleware further down will load the basic page layout
next();
}
The reason why I need !req.accepts('html')
is because of the single page app structure. In other words, when the URL is called for the first time, the whole page layout has to be loaded first.
And when loaded, then the controller on the client side will fire the GET
request (XHR) where a JSON is returned and data is finally presented on the page.
I might be correct there and the above code is fine. But I think there is a bad code smell around req.accepts('json') && !req.accepts('html')
. Do you think so?
It would be nice to add types so that the following would work.
// Accepts: application/hal+json
const accept = accepts(req);
switch(accept.type(['json', 'html'])) {
case 'json':
// would match both application/json and application/hal+json
default:
//
}
const accepts = require('accepts')
const accept = accepts({
headers: {
'accept': 'text/*',
},
})
console.log(accept.types([ 'application/json', 'text/html' ])) // > text/html
console.log(accept.types([ 'application/json', '*/*' ])) // > false
The current default is that:
Treats non-existent headers as *
, which doesn't make sense.
const contentType = accepts(incomingMessage)
.type([
'image/webp',
'image/jpeg',
]) || 'image/jpeg';
In this case, I want to default to the safest option, which is the last entry in the array, or image/jpeg
if nothing is matched.
When no header is present, however, the first option is picked, which is the least likely to be supported.
Ideally, I should be able to pick the fallback option when either header is not present or header value cannot be matched.
In README.md
, all req
after switch
in the code block should be res
.
In order to write a spec compliant content negotiation on the server, we also need to handle a request with e.g., the extreme accept: */*;q=0
, which should return a 406 not acceptable
.
Use cases are for example: a client that can only parse 1 serialization to do something like accept: application/json;q=1,*/*;q=0
. If the server cannot provide an answer, the client will get the convenient 406.
In the accepts package, the server asks the client whether it accepts a certain list of values as follows (as copied from the README.md):
switch (accept.type(['json', 'html'])) {
case 'json':
...
break
case default:
...
break
}
The list ['json','html']
is the server-side list of preferences, yet the client also may have its preferences. Itβs not because a client does not have application/json
in its client-side list, that it cannot parse JSON. So, if the client is asking only for application/xml
, but the server cannot offer that, the functionality should be that application/json
is returned, as this is the preference from the server. Right now, the accepts library would return null, and leave the spec compliant implementation up to the user of the package. Yet probably, that user is not going to go through the pain of parsing the accept header all over again.
An extra note: it may be that the client cannot parse json at all, and wants to indicate that it can only
parse XML.
Instead of accept.type(['a','b','c'])
is false or the format that is mentioned in the accept header of the request, I would only return false (and thus let the developer know it should return a 406) when the client indicated it does not accept any of the server-side representations. This function must return the first representation that is not not acceptable
by the client.
When this is implemented, this would be a breaking change and would require a new major version number of this package.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Content_negotiation
Hi, i want to use this library with not only IncomingMessage
instances.
Node.js 16+ has Fetch API now and it has global constructors such as Request
, Response
, Headers
and other.
Also i see that implementation of this library uses only headers
field from req
parameter.
Maybe we can make this library more abstract, for example we can make next interface changes:
// it is just a variant of interface
declare function accepts(getHeader: (headerName: string) => string | null): Accepts
With this interface we can use this library with instance of any class:
const req1 = new IncomingMessage(/* ... */);
const result1 = accepts(headerName => req1.getHeader(headerName));
const req2 = new Request(/* ... */)
const result2 = accepts(headerName => req2.headers.get(headerName))
Incoming message already has getHeader
method, we can make interface like:
declare function accepts(req: Pick<IncomingMessage, 'getHeader'>): Accepts
And then we can use it now too for IncomingMessage
:
const req = new IncomingMessage(/* ... */);
// no changes in usage
const accept = accepts(req);
And also we can use it easy with Request
instance or any other request value:
const req = new Request(/* ... */);
// easy making wrapper object for use with Request
const accept = accepts({
getHeader: headerName => req.headers.get(headerName)
});
Maybe we can make just TypeScript types of this library more abstract, for example:
declare function accepts(req: Pick<IncomingMessage, 'headers'>): Accepts
Since this module and negotiator
only ever request headers
, do you think it'd be reasonable to document and test on this fact? For instance, I'd like to use this module with https://github.com/blakeembrey/node-servie and other non-node HTTP interfaces.
Hi,
I am getting this
RangeError: Maximum call stack size exceeded
when testing with non-existent accept-headers. that is:
I tried
try {
type = accept.types('html', 'json');
} catch(e) {
// RangeError: Maximum call stack size exceeded
}
to get around the problem, but it still crashes the process
I haven't tried to pimp the request.headers yet, I don't know if it can be done but it looks like it shouldn't
k.
Hi!
Reporting a bug. When I import express, it imports accepts which imports negotiator. However, it seems that version 1.3.8 of accepts cannot find the negotiator dependency. It has to be explicitly installed in the project. Some more details:
Node version: 20.10.0
Express version: 4.17.0
Reverting to accepts 1.3.7 fixes the issue.
accept.types()
supports type-is
-type types. accept.types('json', 'html', 'text/*', 'image/*', 'video/*')
accept[property]()
once so content negotiation can do its job. don't do multiple accept[property]()
sHi π
I'm using express, and i'm trying to figure out how to get the preferred region code (2 letter country code)
do you have any recommendations to deal with this?
almost feel like the negotiator dep should have some kind of feature to retrieve it
In my application, I am negotiation API version by an Accept header that follows the following structure:
application/vnd.<appName>.<version>+json
Is there a way of handling this with accepts? Should it match "json"?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
π Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. πππ
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google β€οΈ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.