'Nextjs with Expressjs POST route not found
I have recently integrated Expressjs with my Nextjs project and was trying to run as POST request to an API.
But I'm getting an error message
Cannot POST /api/auth/signin/`
I do not receive the same when I make a GET request. Based on the way I integrated ExpressJS from a tutorial, I'm curious if the error message for POST requests stems from not attaching the .post() method to the express server in my server side server file. Does this sound like the source of the issue?
ssr-server.js:
const express = require('express')()
const next = require('next')
const bodyParser = require('body-parser')
// Session Management
const session = require('express-session')
const redis = require('redis');
const redisClient = redis.createClient({
host: process.env.REDIS_HOST || 'localhost',
port: process.env.REDIS_PORT || '6379',
url: process.env.REDIS_URL || ''
});
const redisStore = require('connect-redis')(session);
redisClient.on_connect("error", function(error){
console.error(error);
})
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
console.log("Test")
app.prepare()
.then(() => {
const server = express()
// Session Management
server.use(session({
store: new redisStore({client: redis.RedisClient}),
secret: process.env.SESSION_SECRET,
saveUninitialized: false,
resave: false,
cookie: {
secure: process.env.SESSION_SECURE || false,
httpOnly: true,
}
}))
// Form body parsing
server.use(bodyParser.json())
server.use(bodyParser.urlencoded({extended: true}))
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(3000, (err) => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
})
.catch((ex) => {
console.error(ex.stack)
process.exit(1)
})
/api/auth/signin.js:
export default (req, res) => {
if (req.method === 'POST') {
if (res.statusCode = 200){
return res.json({ body: req.body, message: 'Success' })
} else {
return res.json({ message: 'Error on POST'})
}
} else {
return res.json({ message: 'Error' })
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
