简体   繁体   中英

Getting error 405 when sending request on express route in next js

I create routes on Express js in Next js. When i deployed on hosting and sent request on route i getting error 405, but when i do same on localhost everything all right.

I cant understand that is this?

在此处输入图像描述

const express = require('express')
const next = require('next')
const bodyParser = require('body-parser')
const PORT = process.env.PORT || 3000
const dev = process.env.NODE_ENV !== 'production' //true false
const nextApp = next({ dev })
const handle = nextApp.getRequestHandler() //part of next config

nextApp.prepare().then(() => {
const app = express()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const apiRoutes = require("./routes");
app.use('/api', apiRoutes) 
app.get('*', (req,res) => {
    console.log('asdfasdfasdfd')
    return handle(req,res)
})
app.listen(PORT, err => {
    if (err) throw err;
    console.log(`ready at http://localhost:${PORT}`)
})

})

I think your express config has problem. your express server must be like this:

const express = require('express')
const next = require('next')
const handler = routes.getRequestHandler(app)
const app = next({ dir: '.', dev })

app.prepare().then(() => {
  const server = express()
  server.post('/api', (req, res) => {
    handler(req, res, req.url)
  )
  server.get('*', (req, res) => {
    handler(req, res, req.url)
  })

}

check the code for server.get and server.post or other http methods.

Error 405 tells that the method is not allowed.

Vercel can't use custom server with next js https://github.com/vercel/next.js/discussions/13306

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM