I’m trying to build an api, the get all method works, but I’m really struggling to test my post method. I’m using the command curl http://localhost:5000/api/properties -X POST -H "Content-Type: application/json" -d '{"externalId": "hola"}'
and I’m getting the following error:
SyntaxError: Unexpected token ' in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError (C:UsersalberDocumentsUNIWEB2021-Group18backendnode_modulesbody-parserlibtypesjson.js:158:10)
at parse (C:UsersalberDocumentsUNIWEB2021-Group18backendnode_modulesbody-parserlibtypesjson.js:83:15)
at C:UsersalberDocumentsUNIWEB2021-Group18backendnode_modulesbody-parserlibread.js:121:18
at invokeCallback (C:UsersalberDocumentsUNIWEB2021-Group18backendnode_modulesraw-bodyindex.js:224:16)
at done (C:UsersalberDocumentsUNIWEB2021-Group18backendnode_modulesraw-bodyindex.js:213:7)
at IncomingMessage.onEnd (C:UsersalberDocumentsUNIWEB2021-Group18backendnode_modulesraw-bodyindex.js:273:7)
at IncomingMessage.emit (node:events:402:35)
at endReadableNT (node:internal/streams/readable:1343:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
I’ve tried changing the curl command but nothing changes, also tried to do it using postman but also not working.
My code:
index.js:
const express = require("express")
const mongoose = require("mongoose")
const routes = require("./routes/routes")
// Connect to MongoDB database
mongoose
.connect("mongodb://localhost:27017/propertyDB", { useNewUrlParser: true })
.then(() => {
const app = express()
app.use(express.json())
app.use("/api", routes)
app.listen(5000, () => {
console.log("Server has started!")
})
})
routes.js:
const express = require("express")
const Property = require("../models/Property") // new
const router = express.Router()
// Get all posts
router.get("/properties", async (req, res) => {
const properties = await Property.find()
res.send(properties)
})
router.post("/properties", async (req, res) => {
console.log(req.body) //not printing
const property = new Property({
externalId: req.body.externalId,
})
await property.save()
res.send(property)
})
router.get("/properties/:id", async (req, res) => {
const property = await Property.findOne({ _id: req.params.id })
res.send(property)
})
module.exports = router
Does anyone know what am I doing wrong?
Thank you!