简体   繁体   English

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

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

I started learning web development and want to change data on the server when calling functions on the client. 我开始学习Web开发,并且想在客户端上调用函数时更改服务器上的数据。

So this is my example server 这是我的示例服务器

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');
});

and my Handlebars template contains 我的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>

When pressing the button, my client side Javascript calls these functions 当按下按钮时,我的客户端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'
  });
}

but the console says the Ajax post is wrong, just show 404 error. 但控制台表示Ajax发布错误,仅显示404错误。 How can I fix this? 我怎样才能解决这个问题?

In your server side code you are using app.get ie get method while in your Ajax request you are using post method. 在服务器端代码中,您正在使用app.getget方法,而在Ajax请求中,您正在使用post方法。 This is conflicting there in method type. 这与方法类型冲突。

Change your method type in function code 在功能代码中更改方法类型

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