Nodejs ignore request POST made by Angular

0

Context:

I'm using a virtual machine, ng serve is running on port 4200, and nodejs on port 8024, when I try to send data to the server nothing happens, the part of the angle is apparently error-free. When I use postman to send a request (coming from the system out of the virtual machine), there is no problem.

I already tested the url via postman, I enabled 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);
        }
    })
})

Width 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')
      }
    );
  }
    
asked by anonymous 24.06.2018 / 21:57

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 then, if I have returned the API saved user, then just get it inside the then.

If you give an error, you will fall into catch (), then you only have to handle the errors or use the saved user.

    
25.06.2018 / 18:48