簡體   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