Home > Back-end >  How do I post data by JS on nodeJS server
How do I post data by JS on nodeJS server

Time:05-31

I want to post data from form into server without reloading page on clientside.

I have tried something like this, but everytime response from server was {}:

form.addEventListener("submit", (e) => {
  e.preventDefault();
  let data_username = form.querySelector("#username").value,
    data_password = form.querySelector("#password").value;
  fetch("/login/", {
    method: "POST",
    body: JSON.stringify({ username: data_username, password: data_password }),
  });
});

post method on server:

app.post("/login", (req, res) => {
  console.log(req.body);
});

(I can't find solution of this specific case everywhere)

CodePudding user response:

This is a fairly simple fix. The problem is on these lines:

let data_username = form.querySelector("#username").value,
    data_password = form.querySelector("#password").value;

The proper way to select form elements is like this:

form.elements.inputName

So you can change those lines in your code to:

let data_username = form.elements.username.value;
let data_password = form.elements.password.value;

The simplicity of this is probably why your question has several down votes, but in the spirit of actually helping other developers, that is the answer :).

Update: Also, be sure that you're using the body-parsing middleware that comes with Express. If not the request body will remain undefined. To do this add this line to your server-side code:

app.use(express.urlencoded({ extended: true }));

Or if you're using JSON:

app.use(express.json());

CodePudding user response:

I'm still getting errors on client: POST http://127.0.0.1:8080/login/ net::ERR_CONNECTION_RESET and failed to fetch

And also on server terminal: [object Object]

  • Related