Ajax request with Node.js and express

Asked

Viewed 2,839 times

0

I’m completely new working with nodejs, I’ve seen some questions similar to mine but I couldn’t, and I didn’t understand straight would have as someone give me a help?

In case I am trying to send an ajax request using the post method with nodejs.

This is my ajax code:

$.ajax({
                    url: "/components/config/action-send-plano",
                    data: { field1: 'valor 001##', field2: 'valor 002##' },
                    type: 'POST',
                    contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
                    processData: false, // NEEDED, DON'T OMIT THIS
                    beforeSend: function () {
                        $("#" + formName).html(preloaderAzul);
                    },
                    success: function (response) {
                        $("#" + formName).html(response);
                    }
                });

and this is the route to which he sends the request

const express = require('express')
const app = express()
const path = require('path')
const handlebars = require('express-handlebars')

// Config
// Template Engine
app.engine('handlebars', handlebars({ defaultLayout: 'main' }))
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'handlebars')

// Add files
app.use(express.static(__dirname + "/"))

// Body Parser
 const bodyParser = require("body-parser")
 app.use(bodyParser.urlencoded({ extended: false }))
 app.use(bodyParser.json())

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

// Routes
app.get('/', (req, res) => {
    res.render('landingpage')
})

app.post('/components/config/action-send-plano', function (req, res, next) {
    console.log(req.body)
})

In this case, it sends, but I cannot receive the values of field1 and field2, the console returns me all the data referring to the req parameter, but the Fields result does not appear

  • Is using the body-parser?

  • Oops, so I am

  • Opa I think Taffarel already helped you, just an observation, you don’t need to use both app.use(express.json()) and app.use(bodyParser.json()) Only one of the two I think is enough. I haven’t touched Node in a few months, so look at the documentation which one is most up to date and just use it. The same goes for urlencoded.

1 answer

0

The problem is here (using Jquery 3.4.1):

contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS

https://api.jquery.com/jquery.ajax/
I removed the two keys above, and it worked.


NOTE: contenttype, by default, is application/x-www-form-urlencoded; charset=UTF-8, then, as you put false, it does not send in this format, do you understand? And on the server, to receive the post content, it should be in this format: application/x-www-form-urlencoded.


req.body
Contains pairs of key value data sent in the body of the request. By default, it is undefined is filled when you use body analysis middleware, such as express.json() or express.urlencoded().

In accordance with:

app.post('/components/config/action-send-plano', (req, res) => {

let {field1, field2} = req.body;
    console.log(field1)
    console.log(field2)
    res.redirect('/')

//ou também:

console.log(req.param('field1'));
console.log(req.param('field2'));

Minimum example of documentation:

Below is shown how to use the body analysis middleware to fill in req.body.

var express = require('express')

var app = express()

app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded

app.post('/profile', function (req, res, next) {
  console.log(req.body)
  res.json(req.body)
})

Demo: SEU_ARQUIVO_HTML

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel="stylesheet" href="/stylesheets/style.css" />
  </head>
  <body>
    <h1><%= title %></h1>
    <p>Welcome to <%= title %></p>
    <button id="enviar">Enviar</button>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
        $("#enviar").click(function() {

          $.ajax({
            url: "/components/config/action-send-plano",
            data: { field1: "valor 001##", field2: "valor 002##" },
            type: "POST",
            beforeSend: function() {
              //$("#" + formName).html(preloaderAzul);
            },
            success: function(response) {
             // $("#" + formName).html(response);
            },
          });
        });
      });
    </script>
  </body>
</html>

Express NODE

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');

var indexRouter = require('./routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);

app.post('/components/config/action-send-plano', function (req, res, next) {
  let {field1, field2} = req.body;
  res.send(req.body);
})

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

Print: inserir a descrição da imagem aqui

  • Puts in the console.log(req.body) to see what comes and goes here...

  • in console.log(req.body) returns this: {}

  • Are you using the express?

  • Do the following: edit your question and paste all your code that contains this part:app.post('/Components/config/action-send-plan', (req, res) => { console.log(req) console.log(req.field1) console.log(req.field2) res.redirect('/')

  • ready, altered

  • A moment.....

  • See the edition. The problem is in Ajax, the two keys.

Show 2 more comments

Browser other questions tagged

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