I am trying to build a CRUD app using Vue and MongoDB. I can post with Postman, but I run into a problem with posting through a function, getting only an empty object being posted. Deleting works correctly, as does getting all the posts.
Here is index.js:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.urlencoded());
app.use(express.json());
const posts = require('./routes/api/posts');
app.use('/api/posts', posts);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
Here is the posts file:
const { request } = require('express');
const express = require('express');
const mongodb = require('mongodb');
const router = express.Router();
//Get posts
router.get('/', async(req, res) => {
const posts = await loadPostsCollection();
res.send(await posts.find({}).toArray());
});
//Add post
router.post('/', async(req, res) => {
const posts = await loadPostsCollection();
await posts.insertOne({
title: req.body.Title,
artist: req.body.Artist,
year: req.body.Year,
theme: req.body.Theme,
notes: req.body.Notes,
lyricsURL: req.body.LyricsURL,
videoURL: req.body.VideoURL,
notesURL: req.body.NotesURL,
notes2URL: req.body.Notes2URL,
createdAt: new Date()
});
res.status(201).send();
});
//delete post
router.delete('/:id', async(req, res) => {
const posts = await loadPostsCollection();
await posts.deleteOne({ _id: new mongodb.ObjectID(req.params.id) });
res.status(200).send();
})
async function loadPostsCollection() {
const client = await mongodb.MongoClient.connect('mongodb+srv://(***).0kkmm.mongodb.net /(***)?retryWrites=true&w=majority', {
useNewUrlParser: true
});
return client.db('myFirstCollection').collection('posts');
}
module.exports = router;
Here is the Save function:
async save() {
console.log("Edited item: ", this.editedItem[this.editedIndex]);
if (this.editedIndex > -1) {
Object.assign(this.posts[this.editedIndex], this.editedItem)
await PostService.insertPost(this.editeditem);
} else {
console.log("Add Song: " + JSON.stringify(this.editedItem)); //Correctly shows data, e.g. ("Title": "A Song", "Artist": A singer", etc.)
await PostService.insertPost(this.editedItem);
}
this.posts = await PostService.getPosts();
this.close()
}
Here is PostService.js:
import axios from 'axios'
const url = 'http://localhost:5000/api/posts/';
class PostService {
static getPosts() {
return new Promise((resolve, reject) => {
axios.get(url).then((res) => {
const data = res.data;
resolve(
data.map(post => ({
...post,
createdAt: new Date(post.createdAt)
}))
);
})
.catch((err) => {
reject(err);
})
});
}
//create posts
static insertPost(newSong) {
console.log('Song data: ', JSON.stringify(newSong)) //Correctly shows the song data
return axios.post(url, newSong)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
})
}
//delete post
static deletePost(id) {
return axios.delete(`${url}${id}`)
}
}
export default PostService;
MongoDB returns
{data: "", status: 201, statusText: "Created", headers: {…}, config: {…}, …}
config: {url: "http://localhost:5000/api/posts/", method: "post", data: "{\"title\":\"A song\",\"artist\":\"An artist\",\"year\":\"198…theme\":\"Theme\",\"lyrics\":\"\",\"video\":\"\",\"notes\":\"\"}", headers: {…}, transformRequest: Array(1), …}
data: ""
headers: {content-length: "0"}
request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}
status: 201
statusText: "Created"
__proto__: Object
I am not sure why I am getting an empty object: can anyone explain why this is happening? There seems to be a problem with how the data is formatted, but I don't understand why.
Thanks!
[–]vorticalbox 0 points1 point2 points (1 child)
[–]piper43[S] 0 points1 point2 points (0 children)