Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'accepts' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
return function(err, req, res, next) {
const handled = unwrapHandledError(err);
// respect handled error status
let status = handled.status || err.status || res.statusCode;
if (!handled.status && status < 400) {
status = 500;
}
res.status(status);
// parse res type
const accept = accepts(req);
const type = accept.type('html', 'json', 'text');
const redirectTo = handled.redirectTo || `${homeLocation}/`;
const message =
handled.message ||
'Oops! Something went wrong. Please try again in a moment.';
if (isDev) {
console.error(err);
}
if (type === 'html') {
if (typeof req.flash === 'function') {
req.flash(handled.type || 'danger', message);
}
return res.redirectWithFlash(redirectTo);
.then(data => {
if (accepts(req).type(["html", "json"]) === "json") {
res.setHeader("Surrogate-Control", "no-store");
res.setHeader(
"Cache-Control",
"no-store, no-cache, must-revalidate, proxy-revalidate"
);
res.setHeader("Pragma", "no-cache");
res.setHeader("Expires", "0");
res.json(data);
} else {
// XXX: url of sub mounted router points to parents router, so nuxt will try to render 1st depth router's url
req.url = req.originalUrl;
nuxt();
}
})
.catch(error => {
function canDisplayGraphiQL (
event: LambdaAPIGatewayProxyEvent,
params: GraphQLParams
): boolean {
// If `raw` exists, GraphiQL mode is not enabled.
// Allowed to show GraphiQL if not requested as raw and this request
// prefers HTML over JSON.
const request = { headers: mapHeaders(event.headers) }
return !params.raw && accepts(request).types(['json', 'html']) === 'html'
}
loginErrorHandler(req, res, async () => {
const user = (await utils.login(get(req, 'aclManager'), req)) as User;
if (user.role == null) {
throw new TSError(`User ${user.username} missing role `, {
statusCode: 403,
context: {
user,
},
});
}
if (this.playgroundOptions && req.method === 'GET') {
const accept = accepts(req);
const types = accept.types() as string[];
const prefersHTML = types.find((x: string) => x === 'text/html' || x === 'application/json') === 'text/html';
if (prefersHTML) {
const { href: endpoint } = new URL(`${req.baseUrl}${req.url.slice(1)}`, `${req.protocol}://${req.headers.host}${req.baseUrl}`);
const playgroundRenderPageOptions: PlaygroundRenderPageOptions = {
...this.playgroundOptions,
endpoint,
subscriptionEndpoint: endpoint,
settings: {
'editor.reuseHeaders': true,
// @ts-ignore
'schema.polling.interval': 10000,
workspaceName: endpoint,
config: {
app: {
handler: (request, reply) => {
const requestLanguage = Accepts(request).language(Object.keys(renderRequestMap));
request.log(['info'], chalk.green(`Request received for ${request.url.href} (${requestLanguage})`));
return renderRequestMap[requestLanguage](request)
.do(() => request.log(['info'], chalk.green('HTML response ready')))
.subscribe(({ result, statusCode }) => {
// response is sent when this function returns (`nextTick`)
const response = reply(result)
.code(statusCode);
reply.track(response, 'session');
});
},
};
export const getBrowserLang: ParseRequestLang = (request: HapiRequest) => {
const { supportedLangs } = getServerSettings(request);
return Accepts(request).language(supportedLangs);
};
WithLanguages.getInitialProps = async context => {
const languages = context.req
? accepts(context.req).languages()
: navigator.languages
return {
...(Page.getInitialProps ? await Page.getInitialProps(context) : {}),
languages,
}
}
export const getBrowserLang = (request, supportedLangs) =>
Accepts(request).language(supportedLangs);
get accepts() {
if (!this._accepts) this._accepts = accepts(this.req);
return this._accepts;
}
function completedChallenge(req, res, next) {
req.checkBody('id', 'id must be a ObjectId').isMongoId();
req.checkBody('name', 'name must be at least 3 characters')
.isString()
.isLength({ min: 3 });
req.checkBody('challengeType', 'challengeType must be an integer')
.isNumber();
const type = accepts(req).type('html', 'json', 'text');
const errors = req.validationErrors(true);
if (errors) {
if (type === 'json') {
return res.status(403).send({ errors });
}
log('errors', errors);
return res.sendStatus(403);
}
const completedDate = Date.now();
const {
id,
name,