In the name of practice I'm creating a simple application that functions like a text-based game, where "pages" are loaded from a database and displayed. I'm trying to connect my mongo backend with a vue frontend using axios. The database itself is working fine (I checked with mongo shell,) I'm just not posting to the right location from the front end.
I'm sure it's an incredibly obvious fix, but I've gone storeblind working with this project and I need someone to point out what I've been missing. XD
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);
}
},
Fixed! Added a "vue.config.js" file in the frontend with the following:
module.exports = {
devServer: {
proxy: 'http://localhost:3000',
}
}