【问题标题】:Call server side functions from the client in NodeJs从 NodeJs 中的客户端调用服务器端函数
【发布时间】:2018-05-10 10:08:40
【问题描述】:

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

【问题讨论】:

  • 您的服务器已设置为处理获取请求。所以在你的客户端javascript函数中将你的方法类型更改为get
  • 啊,好的,我改一下

标签: javascript node.js ajax post get


【解决方案1】:

在您的服务器端代码中,您使用的是app.get,即get 方法,而在您的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'
  });
}

【讨论】:

  • 如果它现在可以工作,那么请接受我的正确回答。
  • 我会的,只需要再等1分钟
  • 或者路由/incHp/.../decHp/...作为POST通过app.post(...)
猜你喜欢
  • 1970-01-01
  • 2017-06-27
  • 1970-01-01
  • 1970-01-01
  • 2015-01-10
  • 2019-05-22
  • 2017-08-17
  • 2013-06-28
  • 2020-03-08
相关资源
最近更新 更多