Ray
Ray

Reputation: 145

getParameter returns null with Fetch API

My problem is that request.getParameter("username") returns null if I use the Fetch API. Without the Fetch API it works fine and returns the value.

document.getElementById('login').addEventListener('submit', (e) => {
    e.preventDefault();
    fetch('login', {
        method: 'POST'
    })
    .then((response) => {
        return response.text();
    })
    .then((data) => {
        console.log(data);
    })
    .catch(err => {
        console.error(err);
    })
});

What is missing?

This is how I try to catch the value:

@WebServlet("/login")
public class Login extends HttpServlet {
    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println(req.getParameter("username"));
    }
}

username = <input id="username" name="username" placeholder="Username" type="text">

Upvotes: 0

Views: 772

Answers (1)

Robin Zigmond
Robin Zigmond

Reputation: 18249

As I already noted in the comments, you're not actually sending any data with your Ajax call - so it is no wonder that the server cannot see any username property.

All you should need to do to have this work as intended is to replace this:

fetch('login', {
    method: 'POST'
})

with

fetch('login', {
    method: 'POST',
    body: {username: document.getElementById("username").value}
})

This is assuming the username you want to send is the value the user has entered in the "username" input (which I feel is a reasonable assumption). Any other data you want to send with the request should be added as further key-value pairs in the body parameter of the options object you supply to fetch.

Upvotes: 3

Related Questions