将数据插入res.body返回给客户端

时间:2017-05-31 13:14:37

标签: json node.js express response

我的客户端js我执行了一次获取并发送了一些数据。 我试图用res.send或res.json发回结果。

我是否需要创建一个新的json并发送它?

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服务器端将尝试向客户端发送消息。 但是当我这样做时,我做了一个console.log(res)它表明正文是{null,null,null}

客户登录功能

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

编辑:下面的屏幕截图

enter image description here enter image description here

2 个答案:

答案 0 :(得分:1)

您已退回res.json({ message: 'correct' });

使用,

response.message

而不是,

response.body

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

答案 1 :(得分:0)

与Sraven交谈之后,这是一个巨大的帮助。 代码正在发送req,服务器正在响应并包含消息。问题是在客户端,它没有正确得到响应。

以下是工作代码,最终能够产生回复。

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