Search code examples
node.jsangularexpressmean-stackjson-server

POST an item to JSON server db- Angular


I'm trying to POST an Item to my db in my json server. I'm sending the POST request from Angular. When I do so, I get the following error:

Note: when I do the get in a the GET end point it works fine. I'm very new on the server side

POST ERROR 404: Http failure response for http://localhost:3000/addMember: 404 Not Found

SERVER.JS

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
....

app.use(cors());
app.use(express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.disable('x-powered-by');
app.use(xssFilter());
app.use(nosniff());
app.set('etag', false);
app.use(
  helmet({
    noCache: true
  })
);
app.use(
  hsts({
    maxAge: 15552000 // 180 days in seconds
  })
);

app.use(
  express.static(path.join(__dirname, 'dist/softrams-racing'), {
    etag: false
  })
);

app.get('/api/members', (req, res) => {
  request('http://localhost:3000/members', (err, response, body) => {
    if (response.statusCode <= 500) {
      res.send(body);
    }
  });
});

// TODO: Dropdown!
app.get('/api/teams', (req, res) => {
  request('http://localhost:3000/teams', (err, response, body) => {
    if (response.statusCode <= 500) {
      res.send(body);
    }
  });
});

    // Submit Form!
    app.post('/api/members', function(request, response) {
  request.post('http://localhost:3000/members', (err, response, body) => {
    if (response.statusCode <= 500) {
      req.send(body);
    }
  });
});



  app.get('*', (req, res) => {
      res.sendFile(path.join(__dirname, 'dist/softrams-racing/index.html'));
    });

    app.listen('8000', () => {
      console.log('Vrrrum Vrrrum! Server starting!');
    });

ANGULAR

addMember(memberForm: Member) {
    this.http.post(`${this.api}/addMember`, memberForm).subscribe(
      data => {
        console.log('POST Request is successful ', data);
      },
      error => {
        console.log('Error', error);
      }
    );
  }

UPDATE: in my console i see this POST /addMember 404 12.105 ms - 2 and If i go to http://localhost:3000/addMember directly in the browser I see an empty object {} and if I go here http://localhost:3000/ I see this message To access and modify resources, you can use any HTTP method GET POST PUT PATCH DELETE OPTIONS


Solution

  • The issue here is that you are making your POST request to a route which your JSON server does not handle. Change the URL to http://localhost:3000/members, and it should work fine!

    (The routes on a json-server correspond to the elements in your db.json file.)