Working on a simple API. Managed to get the GET & DELETE requests working, but I have some issues with the POST request. Pretty sure this is a noobie mistake, but I'm missing the logic here.
This is the file where all the routes are defined.
import express from 'express';
import fs from 'fs';
const router = express.Router();
'use strict';
let rawdata = fs.readFileSync('api/resources/vehicles.json');
let vehicles = JSON.parse(rawdata);
let vehiclesArray = vehicles.vehicles;
let data = JSON.stringify(vehicles);
fs.writeFileSync('api/resources/vehicles.json', data);
router.get('/', (req, res, next) => {
res.status(200).json(vehiclesArray);
});
router.get('/:id', (req, res, next) => {
let id = req.params.id;
res.status(200).send(vehiclesArray[(id-1)]);
});
router.delete('/:id', (req, res, next) => {
let id = req.params.id;
const removedVehicle = vehiclesArray.splice(id, 1);
res.status(200).json({
message: `Vechicle ${removedVehicle} with id ${id} was removed`
});
});
router.post('/', (req, res, next) => {
let id = vehiclesArray.length 1;
const vehicle = {
"id" : id,
"type" : req.params.type,
"brand" : req.params.brand,
"model" : req.params.model,
"production_year" : req.params.production_year,
"kilometers_driven" : req.params.kilometers_driven,
"price" : req.params.price
};
res.status(201).send({
message: `POSTed new vehicle: ${vehicle}`,
vehicle: vehicle
});
res.status(201).send(vehiclesArray.push(vehicle));
});
export default router;
Inside my POST method I defined the vehicle, but once I try sending it I get the following in Postman, namely a confirmation of an added object and the object, but only with the id property
Can someone please give me a hint maybe on what I'm doing wrong? Do I also need a class declaration? Thanks!
CodePudding user response:
GET below, just to check if the object was indeed added:
Also helpful in my endeavor: https://www.npmjs.com/package/body-parser