【问题标题】:在 vue、mongodb、axios、express 中找不到 POST 404
【发布时间】:2022-01-23 06:46:23
【问题描述】:

以实践的名义,我正在创建一个简单的应用程序,其功能类似于基于文本的游戏,其中“页面”从数据库加载并显示。我正在尝试使用 axios 将我的 mongo 后端与 vue 前端连接起来。数据库本身工作正常(我用 mongo shell 检查过)我只是没有从前端发布到正确的位置。

我确信这是一个非常明显的解决方法,但是我在处理这个项目时已经盲目,我需要有人指出我错过了什么。呵呵

top/backend/server.js

const express = require('../frontend/node_modules/express');
const bodyParser = require("../frontend/node_modules/body-parser");

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));

const mongoose = require('../frontend/node_modules/mongoose');

mongoose.connect('mongodb://127.0.0.1:27017/dragons-world', {
    useNewUrlParser: true
});

//ADD
app.post('/api/pages', async (req, res) => {

  const page = new Page({
    title: req.body.title,
    text: req.body.text
  });

  try {
    await page.save();
    res.send(page);
  }
  catch (error) {
    console.log(error);
    res.sendStatus(500);
  }
});

app.listen(3000, () => console.log('Server listening on port 3000!'));

top/frontend/src/views/Admin.vue

//this method is called on button click in the html
async addPage() {
  console.log("adding page...");
  try {
    await axios.post('/api/pages', {
      title: this.title,
      text: this.text,
    });
    console.log('getting pages...');
    console.log(this.getPages());
    this.getPages();
    console.log("successful!");
    return true;
  }
  catch (error) {
    console.log(error);
  }
},

【问题讨论】:

  • 除非您有代理设置,否则axios.post('/api/pages') 应该是axios.post('<SERVER_URL>/api/pages')。否则,请求将发送到您的前端。
  • 啊!当然。谢谢!

标签: mongodb vue.js express axios http-status-code-404


【解决方案1】:

已修复!在前端添加了一个“vue.config.js”文件,内容如下:

module.exports = {
  devServer: {
    proxy: 'http://localhost:3000',
  }
}

【讨论】:

    猜你喜欢
    • 2020-01-16
    • 2018-12-23
    • 2020-07-14
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 2018-08-14
    • 2019-04-04
    相关资源
    最近更新 更多