7

I am trying to send some data to api via post request.

Frontend Code (React)

handleSubmit = e => {
    e.preventDefault();
    fetch("http://localhost:9000", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        title: this.state.title,
        text: this.state.text
      })
    });
  };

Server (Express)

var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.post("/", urlencodedParser, function(req, res) {
  sql = "INSERT INTO POSTS (id, title, text) VALUES ?";
  var values = [[uuidv1().toString(), req.body.title, req.body.text]];
  con.query(sql, [values], function(err, result, fields) {
    if (err) throw err;
  });
});

When I'm submitting the form, I'm getting this error message from developer console Error Message

I am running client side on localhost:3000 and server side on localhost:9000. Can someone let me know how this problem occurs and how can I fix it?

Ricky Geng
  • 177
  • 1
  • 2
  • 10
  • to fix the first error see the answer from @Arturas, and for the second you should return the response res.send({result}) – Nemer Aug 17 '19 at 13:01

2 Answers2

0

In your package.json file in root directory add proxy property like:

{
    "proxy": "http://localhost:9000"
}
Arturas
  • 192
  • 1
  • 5
  • Worth to mention this works only if you use create-react-app, also dont think this has something to do with the issue. – Damian Busz Aug 17 '19 at 13:27
  • @Arturas Thanks for the reply. I tried that but no luck. Worth to mention the server works fine on port 9000 as I have `var port = normalizePort(process.env.PORT || "9000");` inside `bin/www`. This error only occurs when post request is fired. – Ricky Geng Aug 17 '19 at 13:37
-1

I found the solution. Apparently data is not being posted. So I have to replace headers with

headers: {'Content-Type':'application/x-www-form-urlencoded'}
Ricky Geng
  • 177
  • 1
  • 2
  • 10