AJAX AND XHR FALIED REQUEST PROBLEM

Asked

Viewed 58 times

-3

I have an application on Node.js in an Ubuntu VPS 18.4, but when trying to make a login request for testing, I get a Google Chrome error; "net::ERR_CONNECTION_REFUSED". He tells me he had some problem with the XHR answer.

AJAX code:

let click = document.querySelector('#botao')
let email = document.querySelector('#email')
let senha = document.querySelector('#senha')

click.addEventListener('click', function () {

$.ajax({
type: "POST",
url: "http://localhost:3000/autenticacao",
data: { email: email.value, senha: senha.value },
success: function (data) {
console.log(data.email , data.senha)}});})

Back Code:

module.exports = (app) => {

app.post('/autenticacao', function (req, res) {

let email = req.body.email
let senha = req.body.senha

res.json({email, senha })});}

I am using an NPM package that enables CORS. Below:

const cors = require('cors');
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", 'GET,PUT,POST,DELETE');
app.use(cors());
next();});

Application link: http://45.15.24.156/

Because it does not return the browser console the data entered in the login ?

Thank you !

1 answer

0

When jQuery’s Ajax sends a request it also sends the header x-requested-with (request), so you have to set up on cors() the Access-Control-Request-Headers thus:

Access-Control-Request-Headers: X-Requested-With, Accept, Origin, foo, bar

This of course is an example, it’s not about Node.js and express, as you’re using Cors() so just set up in allowedHeaders with an array, like this:

app.use(cors({
    allowedHeaders: [ 'X-Requested-With', 'Accept', 'Origin', 'foo', 'bar' ]
}));

I noticed that you used a middleware proprio and mixed it with a lib that already does the job:

app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", 'GET,PUT,POST,DELETE');

    app.use(cors());

    next();
});

Either you do "in the hand" or use the lib, if it is to do in the hand dispense the lib, but let’s take an example with the lib, change to just:

const cors = require('cors');

app.use(cors({
    origin: '*',
    methods: ['GET', 'PUT', 'POST', 'PUT', 'DELETE' ],
    allowedHeaders: [ 'X-Requested-With', 'Accept' ]
}));

If you need to allow access to cookies between Xmlhttprequest calls and regular calls (browser forwarding), you need to allow credentials: credentials: true, thus:

app.use(cors({
    origin: '*',
    methods: ['GET', 'PUT', 'POST', 'PUT', 'DELETE' ],
    allowedHeaders: [ 'X-Requested-With', 'Accept' ],
    credentials: true
}));

This in cases where you use authentication systems with Oauth2, such as Facebook-auth, Google-auth, etc.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.