[solved] Post request is not working

Hello. I am trying to save data to mongodb with post request after Firebase fb login. I have a login provider and I am calling it from login page. I think I have a problem with the logic when I am requesting.

  login(){
    this.facebook.login(["email"]).then(res => {
      const token  = firebase.auth.FacebookAuthProvider.credential(res.authResponse.accessToken);
      firebase.auth().signInWithCredential(token).then(fs =>{
        this.isLoggedIn = true;
        this.user = fs;
this.saveToDB();

        alert("Logged in");
      }).catch(ferr => {
        //alert("Firebase error");
      })
    }).catch(err =>{
      alert(JSON.stringify(err));
    });
  }
  saveToDB(){
    let headers = new Headers();
    headers.append('Content-type','application/json');
    let body = { str : this.user.email};
    this.http.post('http://localhost:8080/api/create_user',  JSON.stringify(body) , {headers: headers})
    .subscribe(res =>{
      console.log(res.json());
    });

  }

I tested my backend api with postman and It is working. Here is my post api.

var express  = require('express');
var app      = express();                               // create our app w/ express
var mongoose = require('mongoose');                     // mongoose for mongodb
var morgan = require('morgan');             // log requests to the console (express4)
var bodyParser = require('body-parser');    // pull information from HTML POST (express4)
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var cors = require('cors');

var db = mongoose.connect('mongodb://localhost/mydb');
var Schema = mongoose.Schema;

app.use(morgan('dev'));                                         // log every request to the console
app.use(bodyParser.urlencoded({'extended':'true'}));            // parse application/x-www-form-urlencoded
app.use(bodyParser.json());                                     // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride());
app.use(cors());
 
app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
   next();
});

 var User =  mongoose.model('Users', 
 Schema(
     {
        _id: Schema.Types.ObjectId,
         user_id: String,
         email: String,
         favs: {}
     }),'users'); 


app.post('/api/create_user', function(req, res) {
        User.findOne({email: req.body.str},function(error,users){
            if(error){
                res.send(error);
            }
            if(!users){
               var obj = {email: req.body.str,  favs: {} };
               User.db.collection("users").insertOne(obj, function(err,success){
                if(err) throw err;
                console.log("User added");
                res.send("User added");
               });
            }
            else{
                res.json(users);
            }
        });
});

so, what is the problem?

no data shows up? any errors reported?

The problem was localhost. I changed localhost to my IP adress and it worked fine :slight_smile:

1 Like

thanks for the feedback… yeh… ‘localhost’ is a string that makes this stuff all crazy… phone is a computer with its own ip address…

1 Like