我对Node js很陌生。 尝试构建Web应用程序。当前,使前端和后端分别运行良好,并且两者都托管在同一端口上。前端包含表单,我希望将从表单获取的数据发送到后端。 后端具有前端可以访问的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;
});
});
对此的任何帮助都将不胜感激 谢谢!
答案 0 :(得分:0)
您必须进行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)
}});
});
});