繁体   English   中英

从NodeJ中的客户端调用服务器端功能

[英]Call server side functions from the client in NodeJs

我开始学习Web开发,并且想在客户端上调用函数时更改服务器上的数据。

这是我的示例服务器

const fs = require('fs');
const path = require('path');
const express = require('express');
const exphbs  = require('express-handlebars');

const app = express();

app.engine('handlebars', exphbs({defaultLayout: 'index'}));
app.set('view engine', 'handlebars');

app.use(express.static(path.join(__dirname, 'Public')));

app.get('/profile', function (req, res) { // Render the HTML
  res.render('profile');
});

app.get('/incHp/:id', function (req, res) { // AJAX
  console.log("Ajax => UserId " + req.params.id);
});

app.get('/decHp/:id', function (req, res) { // AJAX
  console.log("Ajax => UserId " + req.params.id);
});

app.listen(8888, function () {
  console.log('Server running on port 8888');
});

我的Handlebars模板包含

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="../Client/profile.js"></script>

<Button class="btn" onclick="increaseHitpoints()">Increase Hitpoints</Button>

<Button class="btn" onclick="decreaseHitpoints()">Decrease Hitpoints</Button>

当按下按钮时,我的客户端Javascript会调用这些函数

function increaseHitpoints(){ // Increase the HP of the User 2312
  $.ajax({
    type: 'POST',
    url: 'http://localhost:8888/incHp/2312'
  });
}

function decreaseHitpoints(){ // Decrease the HP of the User 2312
  $.ajax({
    type: 'POST',
    url: 'http://localhost:8888/decHp/2312'
  });
}

但控制台表示Ajax发布错误,仅显示404错误。 我怎样才能解决这个问题?

在服务器端代码中,您正在使用app.getget方法,而在Ajax请求中,您正在使用post方法。 这与方法类型冲突。

在功能代码中更改方法类型

function increaseHitpoints(){ // Increase the HP of the User 2312
  $.ajax({
    type: 'GET', // change this
    url: 'http://localhost:8888/incHp/2312'
  });
}

function decreaseHitpoints(){ // Decrease the HP of the User 2312
  $.ajax({
    type: 'GET', // change this
    url: 'http://localhost:8888/decHp/2312'
  });
}

暂无
暂无

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

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