This is the third day of Nextjs note-taking. Today I spent some time studying API routing and linking components in Nextjs.
This is the 7th day of my participation in the August Text Challenge.More challenges in August
As we know, Nextjs is a server-side rendering framework that is essentially a Nodejs application, so it naturally inherits everything a server application does: handle API requests, query databases, execute SQL statements, etc. Today we are only going to talk about handling API requests.
How do I configure API routing
Any files in the pages/ API directory will be mapped to/API /* as API endpoints.
Let’s create a new user.ts in the Pages directory:
import type { NextApiRequest, NextApiResponse } from 'next'
type Data = {
name: string,
gender:string,
age:number,
email:string
}
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({
name:'Andrew'.gender:"female".age:20.email:"[email protected]"})}Copy the code
Then, we enter http://localhost:3000/api/user in the browser, received results:
{"name":"Andrew"."gender":"female"."age":20."email":"[email protected]"}
Copy the code
This is how we can configure our mock data. We can also configure baseURL dynamically based on the environment.
Encapsulate SEO-friendly Link components
We know about the Link component in Nextjs, which is used to redirect pages on the client side:
import Link from 'next/link'
function Home() {
return (
<ul>
<li>
<Link href="/">
<a>Home</a>
</Link>
</li>
<li>
<Link href="/about">
<a>About Us</a>
</Link>
</li>
<li>
<Link href="/blog/hello-world">
<a>Blog Post</a>
</Link>
</li>
</ul>)}export default Home
Copy the code
See we put a tag package in the Link tag, in order to SEO friendly, search engines can grab a tag Link. To reuse this feature, we can encapsulate our own anchor components:
/ / component AnchorWrapper TSX
import Link from 'next/link'
import React from "react"
type LinkWrapperPropsType = {
href:string,
}
export const LinkWrapper:React.FunctionComponent<LinkWrapperPropsType> = ({ href, children }) = >{
// Must add passHref to Link
return (
<Link href={href} passHref>
<a>
{children}
</a>
</Link>)}// Component consumption:
import {LinkWrapper} from "./AnchorWrapper"
<LinkWrapper key={menuItem.key} href={menuItem.url}>
// Custom components
</LinkWrapper>
Copy the code
The last
I’ve been learning about Nextjs recently, and its rendering style is very different from traditional client-side rendering, so I have to think about Nextjs development in a different way.
Finally, thanks for reading.