如何将变量从客户端传递到Express api

时间:2017-04-01 02:07:08

标签: javascript node.js express

我对node.js和express表示完全陌生。 我在客户端页面上使用javascript完成了一些计算,我想将生成的数字数组发送到我的node.js服务器应用程序。当我必须发送表单数据时,我只是使用表单操作到我的路线。现在我完全迷失了,不知道从哪里开始。我应该在我的路线中写什么代码,以及如何从我的客户端应用程序传递js变量或数组?

2 个答案:

答案 0 :(得分:1)

将数据数组发送到服务器上运行的Express应用程序,最简单的方法是将其作为JSON对象发送。使用jQuery的一个简单示例如下所示:

客户代码:

    var your_calculated_array = []; // Set your calculated array here
    $.ajax({ 
      type: 'POST', 
      url: 'YOUR_EXPRESS_ENDPOINT', 
      data: { your_data: your_calculated_data }, 
      dataType: 'json',
      success: function (data) { 
        // Handle the response here
      }
    });

服务器端代码(使用正文解析器中间件来解析json正文):

.....

var bodyParser = require('body-parser')
app.use( bodyParser.json() );   

app.post(YOUR_EXPRESS_ENDPOINT, function(req, res) {
    var calculated_data = req.body.your_data
    // ...
})

.....

答案 1 :(得分:1)

简单示例

app.js

var express = require('express')
var app = express()

app.set('view engine', 'pug')

app.get('/', function (req, res) {
  res.render('index')
})

app.post('/example_route', function (req, res) {
  res.send({'msg': 'Hello World!'})
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

视图/ index.pug

doctype html
html
  head
    title= 'HomePage'
    script(src='https://code.jquery.com/jquery-3.2.1.min.js')
  body
    button(onclick='$.post("http://localhost:3000/example_route", function(data) {alert(data.msg);})') Click me!

此主页包含来自cdn的jquery,onclick事件向您的服务器发出POST请求。