简体   繁体   English

从 JavaScript 发送数据到 node.js

[英]Send data from JavaScript to node.js

Below is the JavaScript code.下面是 JavaScript 代码。 How can I send the players array to node.js?如何将玩家数组发送到 node.js?

let players = [];
for(var i=0; i<22; i++){
  players.push($(".card > button").eq(i).attr("value"));
}

Below is the node.js code.下面是 node.js 代码。

const express = require("express");
const bodyParser = require("body-parser");
const mySql = require("mySql");

const app = express();

app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine', 'ejs');

app.get("/play", function(req, res){
  res.render("PlayGame");
});

app.post("/play", function(req, res){
  res.render("PlayGame");
});

I need to catch the players array at /play route in node.js. How can I do that?我需要在 node.js 的/play路线上捕获玩家数组。我该怎么做?

Yes, you can send data from the browser Javascript to your node.js app.是的,您可以将数据从浏览器 Javascript 发送到您的 node.js 应用程序。 You would use an Ajax call and use either the XMLHttpRequest API or the more modern fetch() API to send the data.您将使用 Ajax 调用并使用 XMLHttpRequest API 或更现代的fetch() API 来发送数据。 You would create a route in your nodejs server such as /play and then send the data with the request.您将在您的 nodejs 服务器中创建一个路由,例如/play ,然后随请求发送数据。 Your server will then need to parse the incoming data (depending upon how it was sent) and can then act on it.然后您的服务器将需要解析传入的数据(取决于它是如何发送的)然后可以对其进行操作。

You will also have to decide if you're sending a GET, POST or PUT request (picking what is appropriate based on typical REST design and architecture).您还必须决定是否要发送 GET、POST 或 PUT 请求(根据典型的 REST 设计和架构选择合适的请求)。 If this is starting a game and you're sending a bunch of data with it, then you would probably use a POST request and send the data as JSON in the body of the request.如果这是开始游戏并且您要用它发送一堆数据,那么您可能会使用 POST 请求并在请求正文中将数据作为 JSON 发送。

In Express, here's how you'd receive that type of data:在 Express 中,以下是您接收此类数据的方式:

app.use(express.json());
app.post("/play", (req, res) => {
    console.log(req.body);          // this would be the data sent with the request
    res.send("game started");
});

In the browser, here's how you could send an array of players to your server.在浏览器中,您可以按照以下方式将一组玩家发送到您的服务器。

fetch("/play", {
    method: "POST", 
    headers: {
       'Content-Type': 'application/json'
    },
    body: JSON.stringify(players)
}).then(response => {
    // this line of code depends upon what type of response you're expecting
    return response.text();     
}).then(result => {
    console.log(result);
}).catch(err => {
    console.log(err);
});

See the "Using Fetch" page on MDN for more info.有关详细信息,请参阅 MDN 上的“使用获取”页面

On the client side you would need something like this:在客户端,您需要这样的东西:

const postData = data => {
    const body = JSON.stringify(data);
    return fetch('https://your.url/play', {
        method: 'POST', // GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, cors, same-origin
        cache: 'no-cache', // default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, same-origin, omit
        headers: {
            'Content-Type': 'application/json',
        },
        redirect: 'follow', // manual, follow, error
        referrer: 'no-referrer', // no-referrer, client
        body
    })
        .then(response => response.json()) // parses JSON response into native JavaScript objects
}

const players = ['a', 'b', 'c'];

postData({data: players})
    .then(json => {
        console.log(json);
    })
    .catch(e => console.log(e));

On the server side you would need something like this:在服务器端你需要这样的东西:

app.use(express.json());
app.post("/play", (req, res) => {
    const players = req.body.data;
    ...
    ...
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM