buydadip
buydadip

Reputation: 9407

fetch POST from server using react and passport js

I have a form that I am submitting as a POST request...

<form onSubmit={this.handleLogin.bind(this)} action="/" method="post">
    <div>
        <label>Username:</label>
        <input type="text" name="username"/>
    </div>
    <div>
        <label>Password:</label>
        <input type="password" name="password"/>
    </div>
    <div>
        <input type="submit" value="Log In"/>
    </div>
</form>

so onSubmit I am calling handleLogin which is attempting to submit a form...

handleLogin(){
    fetch('http://localhost:8080', {
        method: 'post',
       body: JSON.stringify({
         username: this.state.username,
         password: this.state.password

      })
   })

}

The form is being submitted to my server, the POST which is supposed to get the request looks as follows...

app.post('/', function(req, res, next) {
    console.log("post");
    passport.authenticate('register', function(err, user, info) {
        console.log("authenticate");
    })(req, res, next);
});

For some reason user is null and info is false, meaning passport is not called properly. By default, passport js expects a username and password, so I'm not sure if I am supposed to pass username and password through the POST request or not.

Here is the rest of my code for passport...

passport.use('register', new LocalStrategy({
    passReqToCallback : true
},
function(req, username, password, done) {

    process.nextTick(function(){

    //find user in DB with this username
        User.findOne({'username': username}, function(err, user) {

            if (err) {

                console.log("Error in registration: " + err);
            }
            //If user already exists in DB
            if (user) {
                console.log("User already exists");
                return done(null, false, req.flash('message', 'User Already Exists'));
            }
            else {

                //if user does not exist, create it
                var newUser = new User();

                newUser.username = username;

                newUser.password = newUser.generateHash(password);
                //console.log("hgeeer");
                //save the user
                newUser.save(function(err) {

                    if (err) {
                        console.log('Error in Saving user: '+err);  
                        throw err;
                    }
                    console.log("User Registered");
                    return done(null, newUser);
                });
            }

        })
    })
}));

What is the proper way of doing this?

Upvotes: 0

Views: 2237

Answers (2)

Lu Tran
Lu Tran

Reputation: 401

  1. For the backend:

passport-local strategy use urlencoded format for the request body. From the doc, you need to specify urlencoded middleware:

app.use(bodyParser.urlencoded({ extended: false }));
  1. For the frontend

when you use JSON.stringify() your param, the fetch api will use the default content-type header as text. In order to send they body as urlencoded format, you can:

fetch(url, {
   ...
   //you don't have to specify the conten-type header, because fetch will use urlencoded format automatically when you use URLSearchParams api
   body: new URLSearchParams(your_json_data_here)
});

Upvotes: 0

abdulbari
abdulbari

Reputation: 6232

I think you didn't give relevant information to the passport

Try to give username and password in Strategy

passport.use('local-signup', new LocalStrategy({
        // by default, local strategy uses username and password, we will override with email
        usernameField : 'email',//changed   accordingly as `username`
        passwordField : 'password',
        passReqToCallback : true // allows us to pass back the entire request to the callback
    },

You can get reference here

Upvotes: 1

Related Questions