ReferenceError: email is not defined

huangapple go评论78阅读模式
英文:

ReferenceError: email is not defined

问题

以下是翻译好的内容:

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",
      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

更新后的错误信息:

Error: SyntaxError: Unexpected token < in JSON at position 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(&quot;/admin-Add-Users&quot;, function(req, res) {
var request = new sql.Request();
// query to the database and get the records
request.query(
&quot;insert into Login (email, password) values (&#39;&quot; +
req.body.email +
&quot;&#39;,&#39;&quot; +
req.body.password +
&quot;&#39;)&quot;,
function(err, recordset) {
if (err) console.log(err);
}
);
res.send({ message: &quot;Success&quot; });
});

AddUsers class

class AddUsers extends React.Component {
constructor() {
super();
this.state = { users: [], email: &quot;&quot;, password: &quot;&quot; };
this.onSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
const data = { email: this.state.email, password: this.state.password };
fetch(&quot;/admin-Add-Users&quot;, {
method: &quot;POST&quot;, // or &#39;PUT&#39;
headers: {
&quot;Content-Type&quot;: &quot;application/json&quot;
},
body: JSON.stringify(data)
})
.then(response =&gt; response.json())
.then(data =&gt; {
console.log(&quot;Success:&quot;, data);
})
.catch(error =&gt; {
console.error(&quot;Error:&quot;, error);
});
}
render() {
console.log(this.state.users);
return (
&lt;div&gt;
&lt;LoginForm&gt;&lt;/LoginForm&gt;
&lt;form&gt;
&lt;input
type=&quot;text&quot;
placeholder=&quot;email&quot;
value={this.state.email}
onChange={e =&gt; this.setState({ email: e.target.value })}
/&gt;
&lt;input
type=&quot;text&quot;
placeholder=&quot;password&quot;
value={this.state.password}
onChange={e =&gt; this.setState({ password: e.target.value })}
/&gt;
&lt;input type=&quot;submit&quot; onClick={this.onSubmit} /&gt;
&lt;/form&gt;
&lt;/div&gt;
);
}
}
ReferenceError: email is not defined

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

Error: SyntaxError: Unexpected token &lt; in JSON at position 0 

答案1

得分: 2

似乎你的React应用程序没有问题。

问题出现在你的API端,你在那里构建了一个insert查询,但实际上没有读取请求的JSON内容(电子邮件和密码字段)。

在生成查询之前,你可以添加以下代码行。

// 创建SQL对象
...
var email = req.body.email;
var password = req.body.password;

...
// 你的查询
英文:

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

答案2

得分: 1

你需要向你的Express应用程序添加中间件以能够解析请求体。尝试将以下内容添加到配置Express的文件中:

app.use(express.json());
英文:

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());

答案3

得分: 0

email and password fields must be retrieved from req.

英文:

email and password fields must be retrieved from req

答案4

得分: 0

这不是一个完整的答案,但问题似乎与CORS(跨源资源共享)有关。我目前不确定解决方案,但我相当肯定这是问题的原因。

感谢您的所有帮助 ReferenceError: email is not defined

英文:

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 ReferenceError: email is not defined

答案5

得分: 0

你好,以下是您的代码的翻译部分:

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);
      }
    }
  });
});
英文:

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

app.post(&quot;/admin-Add-Users&quot;, async (req, response) =&gt; {
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 (&#39;${email}&#39;, &#39;${password}&#39;)`;
console.log(queryString);
request.query(queryString, function(err, recordset) {
console.log(err);
response.status(400);
// response.send(err);
});
response.status(201);
response.send(&quot;User added &quot;);
} else {
response.status(400);
response.send(&quot;no content was provided&quot;);
}
} catch (e) {
console.log(e);
response.status(400);
response.send(e);
}
}
});
});

huangapple
  • 本文由 发表于 2020年1月7日 00:09:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615333.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定