Next.js Discord

Discord Forum

How to redirect from a request, response handler method

Unanswered
Polar bear posted this in #help-forum
Open in Discord
Polar bearOP
1. I have a handler method which accepts form data . This method is written in <root>/pages/api folder.
2. The handler method sends the form data to an external api
3. I am unable to redirect the control to a new location after a successful call to the API. Please find the relevant source code below :
----
import fetch from 'node-fetch';
import { NextResponse } from 'next/server'
export default async function handler(req, res) {

const body = req.body
const dataForm = {

data: {

first_name: ${body.first_name},

}
}
const JSONdata = JSON.stringify(dataForm)
const endpoint = 'http://localhost:1337/api/user'

return new Promise(async (resolve) => {

try {

let response = await fetch(endpoint, {
method: 'POST',
body: JSONdata,
headers: { 'Content-Type': 'application/json' }
});
res.status(200)
return resolve();

}
catch (error) {
res.status(500).end();
return resolve();
}
}).then(
function (value) { onSucces(value); },
function (error) { onError(error); }

);
}

function onSucces(some) {

NextResponse.redirect('http://localhost:3000/')
}

function onError(some) {
console.log(some);
}

0 Replies