coderStew
coderStew

Reputation: 137

ReferenceError: email is not defined

Hi Please help a struggling dev.

I have been trying all day to get this fixed to no avail. Essentially all I want to to do is post from my AddUsers class and for this to be stored through to my sql database. It is a very simple query but has gotten the better off me!The state is updated on change but seems to be an issue with the server.js (error included at bottom of post)

Server.js


app.post("/admin-Add-Users", function(req, res) {
  var request = new sql.Request();

  // query to the database and get the records
  request.query(
    "insert into Login (email, password) values ('" +
      req.body.email +
      "','" +
      req.body.password +
      "')",
    function(err, recordset) {
      if (err) console.log(err);
    }
  );
  res.send({ message: "Success" });
});

AddUsers class

class AddUsers extends React.Component {
  constructor() {
    super();

    this.state = { users: [], email: "", password: "" };
    this.onSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    const data = { email: this.state.email, password: this.state.password };

    fetch("/admin-Add-Users", {
      method: "POST", // or 'PUT'
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
    })
      .then(response => response.json())
      .then(data => {
        console.log("Success:", data);
      })
      .catch(error => {
        console.error("Error:", error);
      });
  }

  render() {
    console.log(this.state.users);
    return (
      <div>
        <LoginForm></LoginForm>

        <form>
          <input
            type="text"
            placeholder="email"
            value={this.state.email}
            onChange={e => this.setState({ email: e.target.value })}
          />
          <input
            type="text"
            placeholder="password"
            value={this.state.password}
            onChange={e => this.setState({ password: e.target.value })}
          />
          <input type="submit" onClick={this.onSubmit} />
        </form>
      </div>
    );
  }
}
ReferenceError: email is not defined

UPDATE: After trying recommendations I have been given I now revive a new error.

Error: SyntaxError: Unexpected token < in JSON at position 0 

Upvotes: 0

Views: 8983

Answers (5)

coderStew
coderStew

Reputation: 137

Hi Everyone thanks for all your help. I fixed this issue by using the following code within my server.js

app.post("/admin-Add-Users", async (req, response) => {
  sql.connect(config, function(err) {
    if (err) {
      console.log(err);
      response.status(400);
      response.send(err);
    } else {
      try {
        // create Request object
        var request = new sql.Request();

        var body = req.body;

        console.log(body);

        if (body) {
          var email = body.email;
          var password = body.password;

          var queryString = `insert into Login (email,password) values ('${email}', '${password}')`;

          console.log(queryString);

          request.query(queryString, function(err, recordset) {
            console.log(err);
            response.status(400);
            // response.send(err);
          });

          response.status(201);
          response.send("User added ");
        } else {
          response.status(400);
          response.send("no content was provided");
        }
      } catch (e) {
        console.log(e);
        response.status(400);
        response.send(e);
      }
    }
  });
});

Upvotes: 0

coderStew
coderStew

Reputation: 137

This is not a complete answer but it turns out the issue is related to CORS. I am not sure of the solution at this point ,but I am fairly sure this is the cause.

Thanks for all your help :)

Upvotes: 0

Travis James
Travis James

Reputation: 1939

You need to add middleware to your express app to be able to parse request body's.

Try adding this to the file where you configure express:

    app.use(express.json());

Upvotes: 1

pritam
pritam

Reputation: 2558

It seems like there is nothing wrong in your React app.

The problem is at your API end where you're formulating an insert query without actually reading the request json content (email & password) fields.

You could add following lines before the query is being generated.

// create sql obj
...
var email = req.body.email;
var password = req.body.password;

...
// your query

Upvotes: 2

Aleksandr
Aleksandr

Reputation: 431

email and password fields must be retrieved from req

Upvotes: 0

Related Questions