Angular 4 and Nodejs Express - Problem with CORS

Asked

Viewed 104 times

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, Undefined is coming. Could it be CORS problem? I set setHeader and ran some tests. Before it was giving permission error and now it has been solved. 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);
    });
}

}

Someone’s had that problem before?

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);
    });
}

Browser other questions tagged

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