0

I want to check username/password with a post request using axios like this :

function axiosCall() {
    axios.post('/login', {
        username: document.getElementById("username").innerText,
        password: document.getElementById("password").innerText
    })
        .then(function (problem) {
            if (problem.toString() === "username") {
                lespanUsername.innerHTML = "Pseudo incorrect !";
            } else if (problem.toString() === "password") {
                lespanPassword.innerHTML = "Votre mot de passe est incorrect !";
            }
        })
}

But my express post :

app.post('/login', urlEncodedParser, (req, res) => {
    let username = req.body.username;
    let password = req.body.password;
    if (users.existUser(username)) {
        if (users.validUser(username, password) === true) {
            res.status(200)
            res.redirect("/");
        } else {
            res.status(401)
            res.send("password")
        }
    } else {
        res.status(401)
        res.send("username")
    }
});

Sending html instead of a variable and reloading my page. :

html

Does anyone have an answer, I haven't found a solution despite a lot of searching. The send("username") works on the examples I found online. Thanks in advance !

Amaroke
  • 61
  • 8
  • 1
    Once you use `axios` the browser will no longer be responsible for normal behaviour such as loading a web page (from your `res.redirect()`) etc. If you want to use `res.redirect()` you should not use axios but instead use a form (normal form behavior without any javascript). If you want to use axios you need to handle after login behaviour using your own javascript code (eg. `window.location.href = "/"` etc.) – slebetman Oct 23 '22 at 11:55
  • I couldn't find a way to return data from my post to my login page (without using ?wrong=username in URLs), that's why I was trying with axios. There is a way with the form without axios, so that my error message tells me "there is no user with this nickname". – Amaroke Oct 23 '22 at 12:03
  • HTML forms should do that for you by default. But normally forms are not url encoded, they're multipart form data. You can specify to have the form submitted as url encoded by using the `enctype` attribute (eg: `
    – slebetman Oct 23 '22 at 12:11
  • Note though that with forms you are always sending back a **COMPLETE** html page. So if you want to send back a page that says "there's no user with this nickname" you need to do `res.send('your page design here
    There is no user with this nickname
    ')`
    – slebetman Oct 23 '22 at 12:13
  • Yes, but it will refresh my page and I would just like the "bad password" messages to be added with some js in a span. – Amaroke Oct 23 '22 at 12:14
  • If on the other hand you want to handle it in javascript you must handle **EVERYTHING** in javascript. eg: `(if (problem=='username') {invalidUser()} else if (problem=='password') {invalidPassword()} else if (problem=='successful') {document.location.href = "/"}` but that means in Express you don't try to redirect to "/" because you are doing that in your browser, instead you send the string `"successful"` – slebetman Oct 23 '22 at 12:16
  • `I would just like the "bad password" messages to be added with some js in a span` With the appropriate templating language in the backend and good session handling you can emulate/fake adding the message to some span in the backend by sending a complete HTML with the span containing the message. The choice is yours: handle everything in the backend (thereby having the ability to use backend related functions like `res.redirect()`) or handle everything in the browser (thereby using DOM functions to do things like redirecting to other pages) – slebetman Oct 23 '22 at 12:20

1 Answers1

4

You have six separate problems here.

reloading my page

The code you've supplied won't do that.

The most likely reason is that you are calling axiosCall when a form is submitted (or when a submit button is clicked, which amounts to the same thing) and failing to prevent the default behaviour for that.

HTML

See the documentation for send:

When the parameter is a String, the method sets the Content-Type to “text/html”

In HTML, a number of tags (including the start and end tags for html, head and body`) are optional. The browser is generating them when it parses the HTML document you are supplying.

Use res.json instead. axios will parse a JSON response automatically.


Problems you have but haven't discovered yet

Form encoding

You have urlEncodedParser.

A form submission (see the first part of this answer) will, by default, use URL encoding.

Axios will use JSON encoding. You'll need to change the middleware when you get your Axios request to replace the form submission request.

innerText

You are, presumably, reading the data from input elements.

They don't have innerText, they have values.

response object

.then(function (problem) {
            if (problem.toString() === "username") {

The resolve value of the promise will be a response object.

You need to access its data property. If you stringify the response you'll get "[Object object]" which won't match "username".

redirecting

res.redirect("/");

A redirect means "What you asked for can be found here".

It does not mean "The browser viewport should navigate to this URL".

That will cause the browser to request / (which I'm assuming is your homepage, an HTML document) and supply it to your JavaScript. It won't display it.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Ok I understood the second problem! And I replaced the .send with a .json. But not the first i try this : ``` const boutonConnexion = document.querySelector("#boutonConnexion"); boutonConnexion.addEventListener("click", callToAxios, false); function callToAxios(event) { axiosCall(); event.preventDefault(); } ```js But nothing change. – Amaroke Oct 23 '22 at 11:50
  • Ok for innerText and the data property too, and thanks, but same for urlEncodedParser and res.redirect i do not really understand cause i use it everywhere and its works fine. What should I use instead? Because without the urlEncodedParser my res.body is empty. – Amaroke Oct 23 '22 at 11:55
  • 1
    Assuming that you are now dealing with the request made by axios and not the request made by submitting a form, then you neeed a JSON parsing middleware. https://expressjs.com/en/api.html#express.json – Quentin Oct 23 '22 at 12:29
  • Ok I documented and tested all the points you listed, and I managed to make it work respecting everything you said! Thank you very much for all these precisions! – Amaroke Oct 23 '22 at 16:24