Angular 4 and Nodejs Express - Problem with CORS

1

Hello, I have two applications that run locally on different ports. One application is for API's and another is the web part.

When I send the form data to my typescript service, the data is arriving correctly. But in the API controller, it's coming undefined. Can it be CORS problem? I put setHeader and did some testing. Before I was giving permission wrong and now it has been resolved. However, the undefined object problem remains.

The web application goes to a typescript service and this service in turn calls the API.

I'm setting the header like this

app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');

res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});

Service code

  @Injectable()
  export class UserService {
   constructor(private http:Http) { }

   save(user: User) {
     let cpHeaders = new Headers({ 'Content-Type': 'application/json' 
     });
     let options = new RequestOptions({ headers: cpHeaders });
     this.http.post("http://localhost:4000/users", 
     user, options)
    .subscribe(
        data => {
        console.log("ddddd");
        });

        return user;
}

}

And the API code is this:

module.exports = class UserController {
 save(user){
    console.log('esse user vem undefined' + user)
    user.userName = user.email.split("@")[0];
    models.User.create(user)
    .then(function () {
        console.log('ok')
    })
    .catch(function (err) {
        console.log(err);
    });
}

}

Has anyone ever had this problem?

    
asked by anonymous 03.03.2018 / 06:26

1 answer

0

Try this

save(req, res ){
    const user = { user.userName: req.body.email};
    user.userName = user.email.split("@")[0];
    models.User.create(user)
    .then(function () {
        console.log('ok')
     })
    .catch(function (err) {
        console.log(err);
    });
}
    
06.03.2018 / 23:07