【问题标题】:Getting error 405 when sending request on express route in next js在下一个 js 中通过快速路由发送请求时出现错误 405
【发布时间】:2020-11-22 17:01:03
【问题描述】:

我在 Next js 中的 Express js 上创建路由。当我在主机上部署并在路由上发送请求时,我收到错误 405,但是当我在 localhost 上执行相同操作时,一切正常。

我不明白这是?

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}`)
})

})

【问题讨论】:

    标签: javascript reactjs express http next.js


    【解决方案1】:

    我认为您的快速配置有问题。 你的快递服务器必须是这样的:

    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)
      })
    
    }
    

    检查server.getserver.post 的代码或其他http 方法。

    错误 405 表明该方法不被允许。

    【讨论】:

    • 我的快速配置是这样的,但我还添加了 server.use("/api", require(".routes/api")) 来连接我的路由
    • 你在 nextjs 中的 cors 中间件初始化是什么?
    • 我在这个项目中不使用 cors。重要吗?
    • 不不重要。使用GET 方法测试,看看它是否有效。
    • 如果我发送 get 请求我得到 404,如果我发送 post 请求我得到 405
    【解决方案2】:

    Vercel 不能使用带有下一个 js 的自定义服务器 https://github.com/vercel/next.js/discussions/13306

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-05
      • 2019-04-20
      • 2021-12-14
      • 2013-08-25
      • 2022-07-07
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多