简体   繁体   English

将 jquery 前端连接到 nodejs 后端

[英]Connecting jquery frontend to nodejs backend

I'm fairly new to node js.我对节点 js 相当陌生。 Trying to build a web app.尝试构建 web 应用程序。 Currently, have the frontend and backend working well individually and both are hosted on the same port.目前,让前端和后端单独运行良好,并且两者都托管在同一个端口上。 Frontend contains forms and I want the data acquired from the form to be sent to the backend.前端包含 forms,我希望将从表单获取的数据发送到后端。 Backend has api that the frontend can access but both are failing to connect.后端有 api 前端可以访问,但两者都无法连接。

app.use('/cssFiles',express.static(__dirname + '/testhomepg/testhomepg/'));
app.get('/', function(req, resp) {
    resp.sendFile('home.html', {root:path.join(__dirname, '../Frontend/testhomepg/testhomepg')});
})

app.get(/^(.+)$/, function(req,resp) {                   // getting data from the form
    console.log(req.params[0] + ' GET')
    resp.sendFile(req.params[0], {root:path.join(__dirname)});
})

app.post('/register', function(req, resp) {              // Trying to connect to the backend
    console.log('Data:' + JSON.stringify(req.body));
    resp.json({message: 'message recieved!!!'})
})

$(function() {                                                // function called on clicking 'Submit'
    $('form').submit(function() {
      
        var obj1 = $('form').serializeObject();
        var obj2 = {person: "tutor"};
        var data = $.extend({}, obj1, obj2);

        $(location).attr('href', './thankyou.html')
        return false;
    });
});

Any help on this is much appreciated Thank you!非常感谢您对此的任何帮助谢谢!

you have to make ajax call to connect to backend api您必须拨打 ajax 调用才能连接到后端 api

$(function() {                                                
$('form').submit(function() {
    var obj1 = $('form').serializeObject();
    var obj2 = {person: "tutor"};
    var data = $.extend({}, obj1, obj2);    
    $.ajax({type: 'POST', url: "/register", data,
         success: function(result){
         console.log(result)
        }});
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM