отправка почтового запроса с использованием ajax на nodejs - PullRequest
0 голосов
/ 23 сентября 2019

Я пытаюсь отправить данные с помощью ajax на nodeJS:

var express = require('express');
var app = express();
var path = require('path')
app.use(express.urlencoded())
const router = express.Router();

router.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/client.html'));
  //__dirname : It will resolve to your project folder.
});


//add the router
app.use('/', router);

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

    var obj = {};
    console.log('body: ' + JSON.stringify(req.body.title));
    res.send(req.body);
});
app.listen(3000);

app.js

    <html>
    <head>
        <title>jsonp test</title>
        <script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>      
        <script type="text/javascript">
            $(function(){               
                $('#select_link').click(function(e){
                    e.preventDefault();
                    console.log('select_link clicked');
                    var data = {};
                    data.title = "title";
                    data.message = "message";
                    $.ajax({
                        type: 'POST',
                        data: JSON.stringify(data),
                        contentType: 'application/json',
                        url: 'http://localhost:3000/endpoint',                      
                        success: function(data) {
                            console.log('success');
                            console.log(JSON.stringify(data));
                        }
                    });

                });             
            });
        </script>
    </head>
    <body>
        <div id="select_div"><a href="#" id="select_link">Test</a></div>    
    </body>
</html>

Не понимаю, почемуне получает данные на стороне сервера, у кого-нибудь есть подсказка, как я могу это сделать?

спасибо заранее!

1 Ответ

0 голосов
/ 23 сентября 2019

Отправьте data без stringify

$.ajax({
  type: 'POST',
  data: data,
  contentType: 'application/json',
  url: 'http://localhost:3000/endpoint',
  success: function (data) {
    console.log('success');
    console.log(JSON.stringify(data));
  }
});

У вас будет доступ к data.title с req.body.title

app.post('/endpoint', function (req, res) {
  console.log('body: ' + req.body.title);
  //...
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...