Nodejs ignores request POST made by Angular

Asked

Viewed 40 times

0

Context:

I’m using a virtual machine , ng serve is running on port 4200, and the nodejs on port 8024, when I try to send data to the server nothing happens, the angular part apparently shows no errors. When I use the postman to send a request (coming from the system outside the virtual machine), no problem occurs.

I already tested the url via Postman, enabled the CORS and nothing works.

App.js

var express = require('express');
var app = express();
const project = require('./controllers/ProjectController');
const auth = require('./controllers/AuthController');
const task = require('./controllers/TaskController');
var bodyParser = require('body-parser');
const cors = require('cors');

app.use(cors());
app.options('*', cors());
app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(auth);
app.use(project);
app.use(task);

module.exports = app;

URL that was used:

router.post('/register',(req,res) =>{
    console.log('teste'); //nunca é ativada
    let salt = bcrypt.genSaltSync(10);
    let hashedPassword = bcrypt.hashSync(req.body.password, salt);
    var user = {
        id:0,
        login:req.body.login,
        name:req.body.name,
        role:'user',
        password:hashedPassword
    }

    let query = 'insert into user set ?';
    db.query(query,user,(err)=>{
        if(err){
            res.sendStatus(400);
            throw err;
        }else{
            res.sendStatus(201);
        }
    })
})

Stretch used in Angular :

  registerUser(user: User) {
    console.log(user); // sempre funciona sem erros
    const body = new HttpParams()
      .set('login', user.login)
      .set('password', user.password)
      .set('name', user.name);

    return this.http.post(this.url,
      body.toString(),
      {
        headers: new HttpHeaders()
          .set('Content-Type', 'application/x-www-form-urlencoded')
      }
    );
  }

1 answer

1


Try to use it that way

salvar(user: User): Promise<User> {
    return this.http.post(this.url, user)
      .toPromise()
      .then(usuarioSalvo=> usuarioSalvo.json())
      .catch(erro => {
        return Promise.reject(`Erro ao salvar o user: ` + erro);
      });
  }

When saving successfully will fall into the then, if I had returning from the saved user API, then just pick it up inside the then.

In case of error, you will fall in the catch(), then just handle the errors or use the saved user.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.