Search code examples
node.jsangularexpressxmlhttprequest

Can't route XHR requests, while URL in browser is working


I'm trying to develop a REST API in TypeScript with NoteJS and Express.

So far I've managed to get the API work on localhost, and if I navigate to http://localhost:8080 everything works.

In particular, I've set up the route http://localhost:8080/newwletter/subscribe, and if I navigate with the browser to that page a new (fake) subscriber is correctly added to the database (meaning the whole logic works).

If I make a XHR call from the client web app, however, all request are handled by the rute handler '*'.

This is the current code:

import express = require('express');

const app = express();

const newsletterRoutes = express.Router();

newsletterRoutes.get('/subscribe', async (req, res) => {
  console.log('req', req);
  res.send(await new Subscribers().add());
});

app.use(function (req, res, next) {

  res.setHeader('Content-Type', 'application/json');
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

  next();
});

app.use('/newsletter', newsletterRoutes);

app.use('*', (req, res) => {
  console.log(req.params);
  res.status(200).send('No valid url').end();
});

On the client side, I'm making the request in an Angular 6 app, like so:

this.http.post(url, payload, {
  headers: new HttpHeaders().set('Content-Type', 'application/json')
})
.toPromise()
.then(response => console.log(response))
.catch(err => console.error('XHR Failed to connect to API', err));

Solution

  • Your route is defined for GET methods, while your client is issuing a POST request.

    Do one of these:

    • Define newsletterRoutes.post('/subscribe', ...)
    • Call this.http.get(url, ...)