'Why use Next.js API route with an external API?
I am new in Next.js.
I want to know what is the use of export default function handler because we can directly call the API using fetch.
In my HTML code I put below code. When I click on submit button sendformData() function will be called.
<input type="button" value="Submit" onClick={() => this.sendformData()} ></input>
sendformData = async () => {
const res = await fetch("/api/comments/getTwitFrmUrl?twitUrl=" + this.state.twitUrl, {
headers: {
"Content-Type": "application/json",
},
method: "GET",
});
const result = await res.json();
this.setState({ data: result.data });
};
When sendformData function is called, it calls /api/comments/ file and calls the function.
Here is the /api/comments/[id].js file code.
export default async function handler(req, res) {
if (req.query.id == 'getTwitFrmUrl') {
const resData = await fetch(
"https://dev.. .com/api/getTwitFrmUrl?twitId=" + req.query.twitUrl
).then((response) => response.text()).then(result => JSON.parse(result).data);
res.status(200).json({ data: resData });
}
else if (req.query.id == 'getformdata') {
console.log('getformdata api');
res.status(200).json({ user: 'getuserData' });
}
}
When I put the below code in the sendformData same response will be retrieved. So why we need to call
export default function handler function?
sendformData = async () => {
const res = await fetch(
"https://dev.. .com/api/getTwitFrmUrl?twitId=" + req.query.twitUrl
).then((response) => response.text()).then(result => JSON.parse(result).data);
const result = await res.json();
this.setState({ data: result.data });
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

