0

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 
Emile Bergeron
  • 14,368
  • 4
  • 66
  • 111
coderStew
  • 107
  • 8

5 Answers5

2

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

pritam
  • 1,904
  • 1
  • 15
  • 24
1

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());
Travis James
  • 1,598
  • 4
  • 18
0

email and password fields must be retrieved from req

Aleksandr
  • 321
  • 2
  • 7
  • 1
    Thanks for the advice. How would I implement this ? – coderStew Jan 06 '20 at 16:21
  • ``` 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" }); });``` – coderStew Jan 06 '20 at 16:23
  • solution [link](https://stackoverflow.com/a/59615541/12661052) – Aleksandr Jan 06 '20 at 16:26
  • Error: SyntaxError: Unexpected token < in JSON at position 0 – coderStew Jan 06 '20 at 16:26
  • Please add some more explanation to your answer. What do you mean by "retrieved from req"? – Nico Haase Jan 06 '20 at 16:30
  • req.body is a json build. it must be transformed into an object. Use app.use (express.json ()); – Aleksandr Jan 06 '20 at 16:33
0

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 :)

coderStew
  • 107
  • 8
0

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);
      }
    }
  });
});
coderStew
  • 107
  • 8