0

with my client js i have perform a fetch and send along some data. And i've attempted to do a res.send or res.json to send a result back.

Do I need to create a new json and send it?

Express Server

const express = require('express');
const app = express();

const pg = require('pg');
const conString = 'postgres://postgres:password@localhost/postgres';

const bodyParser = require('body-parser');

app.use(bodyParser.json()); //support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true})); //support encoded bodies

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

app.listen(3000, function () {
  console.log('Server listening on port 3000!');
});

app.post('/', function(req, res){

  var uname = req.body.username;
  var pw = req.body.password;

  QueryByUserName(uname, function(err, result){
    if(err){
      console.error('error happened', err);
      //handle error
    }

    if(uname == result.username){
      //name is in our database
      if(pw == result.password){
        console.log("User and Password Correct!");
        res.json({ message: 'correct' });
      } else {
        console.log("Password Incorrect!");
        res.json({ message: "incorrect" });
      }
    } else if(result.username == "undefined"){ //placeholder
      console.log("username does not exist");
      res.send( {message: "dne"} );
      console.log(res);
    }

  });
});

function QueryByUserName(input, callback) {
  pg.connect(conString, function(err, client, done){
    if(err){
      callback(err);
      return;
    }

    client.query(SelectAll(), function(err, result){
      //Query database for all usernames
      done();

      var isFound = false;

      for(var x = 0; x < result.rows.length; x++){
        //loop through all usernames from database.
        if(result.rows[x].username == input){
          isFound = true;
          //username exists, now we obtain the rest of the data.
          client.query(findDataInDatabase(input, '*'), function(err, result){
            done();

            if(err){
              callback(err);
              return;
            }

            console.log(result.rows[0]);
            callback(null, result.rows[0]);
            //return all information regarding user to callback function
          });
        } else if(x == (result.rows.length - 1) && !isFound){
          callback(null, {username: "undefined"}); //placeholder
          //Username does not exist in database
        }
      } //end of For Loop

    });
  });
}

function findDataInDatabase(username, WhatWeLookingFor) {
  return 'select ' + WhatWeLookingFor + ' from users where username = \'' + username + '\'';
}

Express server side will try to send a message to the client. but when I do this i did a console.log(res) it shows that the body is { null, null, null}

Client login Function

handleLogin: function(){
    let fetchData = {
      method: "post",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },

      body: JSON.stringify({
        username: this.state.user,
        password: this.state.password,
        message: null
      })
    }

    var fromServer = fetch('http://localhost:3000/', fetchData)
    .then(function(response){
      if( !response.ok){
        throw Error (response.statusText);
      }
      console.log(response);
      console.log(response.message);
      console.log(response.body);
      console.log(response.body.text);
      return response.json();
    })
    .catch(error => console.log("there was an error --> " + error));
  },

Edit : Screenshots below

enter image description here enter image description here

Eric
  • 682
  • 2
  • 11
  • 23

2 Answers2

1

Since you have returned, res.json({ message: 'correct' });

use,

response.message

Instead of,

response.body

  var fromServer = fetch('http://localhost:3000/', fetchData)
     .then(response => response.json())
     .then(response => {
        console.log(response.message);
     })
Sravan
  • 16,897
  • 2
  • 24
  • 48
  • response.message returns undefined. – Eric May 31 '17 at 14:03
  • what is returned from `console.log(response)` – Sravan May 31 '17 at 14:03
  • i logged response, response.message, response.body, and response.body.text. screenshot posted in question. – Eric May 31 '17 at 14:08
  • check if you are getting data in `result varialbe`, `console.log(result)` in `QueryByUserName` result and check in `terminal` – Sravan May 31 '17 at 14:12
  • yes i am getting data from that. since the result response is massive ill just post the body. "body: { username: 'someUser', password: 'asdf', message: null }," – Eric May 31 '17 at 14:15
  • result has `body` key, so `result.body.username` – Sravan May 31 '17 at 14:17
  • the server side is working, i'm able to retrieve data from database and perform logic, i'm now trying to send a response back to the client. result.body.username will give me the username i typed into the input form. – Eric May 31 '17 at 14:20
  • do you have any data in `result.username` in the line `if(uname == result.username){` – Sravan May 31 '17 at 14:24
  • yes that portion works. uname is the data entered from client's input form. and result.username is the data retrieved from the database. – Eric May 31 '17 at 14:32
  • I've posted the result of printing out uname and result.username, also the response from database. when i typed in correct username/wrong password, and correct username/correct password in the client's input field and request a response – Eric May 31 '17 at 14:34
  • I think you should return. `return res.send({ message: 'correct' });` or `return res.send({ message: 'correct' });` – Sravan May 31 '17 at 14:36
  • when i try res.send i get the exact same result as res.json in my client console. – Eric May 31 '17 at 14:38
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/145561/discussion-between-sravan-and-user3307553). – Sravan May 31 '17 at 14:39
  • checked with `return?` `return res.json({ message: 'correct' });` – Sravan May 31 '17 at 14:45
  • @Eric, you can accept and vote my answer, if you find it useful. :) – Sravan Jun 01 '17 at 05:08
0

After talking to Sraven, who was a huge help. The code is sending a req, and the server is responding with a response with the message included. The problem was on the client side where it was not getting the response correctly.

Below is the working code and was able to finally produce a response.

var fromServer = fetch('http://localhost:3000/', fetchData)
.then(response => response.json())
.then(response => {
  console.log(response.message);
})
Eric
  • 682
  • 2
  • 11
  • 23