[Next.js] Add Middleware to an API Route Created with next-connect
<p>We'll learn how to create a middleware function for next-connect. This middleware will work at the route level, for example, for every request that hits the /api/next-connect-middleware endpoint, or at the HTTP verb level, GET /api/next-connect-middleware</p><div class="cnblogs_code">
<pre>import nextConnect from 'next-connect'<span style="color: rgba(0, 0, 0, 1)">
const withAuthentication </span>= (req, res, next) =><span style="color: rgba(0, 0, 0, 1)"> {
</span><span style="color: rgba(0, 0, 255, 1)">if</span> (!<span style="color: rgba(0, 0, 0, 1)">req.headers.authentication) {
</span><span style="color: rgba(0, 0, 255, 1)">return</span> res.status(401).json({message: 'error'<span style="color: rgba(0, 0, 0, 1)">})
}
</span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> next()
}
const handler </span>=<span style="color: rgba(0, 0, 0, 1)"> nextConnect()
<span style="background-color: rgba(255, 255, 0, 1); color: rgba(255, 0, 255, 1)"><strong>.use(withAuthentication)</strong></span>
.get(withAuthentication , (req, res) </span>=> res.json({message: 'get'<span style="color: rgba(0, 0, 0, 1)">}))
export </span><span style="color: rgba(0, 0, 255, 1)">default</span> handler</pre>
</div>
<p> </p><br><br>
来源:https://www.cnblogs.com/Answer1215/p/16096685.html
頁:
[1]