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

时间:2017-11-27 08:13:28

标签: javascript node.js ajax post get

我开始学习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错误。我该如何解决这个问题?

0 个答案:

没有答案