【问题标题】:NuxtJS, ExpressJS - how to connect to endpoint correctly?NuxtJS,ExpressJS - 如何正确连接到端点?
【发布时间】:2022-01-12 08:15:43
【问题描述】:

我正在尝试连接到端点,我有“POST http://localhost:3000/api/post 404 (Not Found)”

将中间件 postRoutes 连接到 ./api/index.js:

app.use('/post', postRoutes)

export default {
  path: '/api',
  handler: app
}

postRouter 文件 ./api/routes/post.routes.js:

const { Router } = require('express')
const ctr = require('../controllers/post.controller')
const router = Router()

router.post('/api/post', ctr.create)

module.exports = router

vue 页面:

const formData = {
 title: this.form.title,
 text: this.form.text
}
try {
 await this.$store.dispatch('post/create', formData)
} catch (e) {}

所以我向商店 ./store/post.js 发出发布请求:

export const actions = {
  async create({ commit }, formData) {
    try {
      return await this.$axios.$post('/api/post', formData)
    } catch (e) {
      commit('setError', e, { root: true })
      throw e
    }
  }
}

【问题讨论】:

  • 在调用 axios 时,在 /store/post.js 文件中,您是否尝试放置完整的本地 URL(http://locallhost:3000/api/post 而不是相对的 /api/post 在这里)?

标签: express axios nuxt.js


【解决方案1】:

如果您在 axios 中编写完整路径,它将起作用。您也可以在状态中为基本 url 创建字段并在操作中使用它。

return await this.$axios.$post('http://localhost:3000/api/post', formData)

【讨论】:

    【解决方案2】:

    /api/post/api/post 上观察到中间件之前,我通过编辑router.post 解决了这个问题:

    router.post('/', ctr.create)
    

    我的请求也是这样的:

    return await this.$axios.$post('/api/post', formData)
    

    【讨论】:

      猜你喜欢
      • 2018-02-14
      • 2019-10-12
      • 2022-07-28
      • 2016-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-07
      相关资源
      最近更新 更多