简体   繁体   English

需要将数据从NodeJS服务器发送回JQuery客户端

[英]Need to send data back from a NodeJS server to a JQuery client

I'm trying to send some files and data back from a NodeJS server to a client that works in JQuery. 我正在尝试将一些文件和数据从NodeJS服务器发送回在JQuery中工作的客户端。 I use res.sendfile() to return files from the NodeJS server, but that downloads the file on the client computer. 我使用res.sendfile()从NodeJS服务器返回文件,但是在客户端计算机上下载文件。 I only want to send the file back to the JQuery code (Written in Typescript) and enable it being manipulated or rendered by the JQuery code. 我只想将文件发送回JQuery代码(在Typescript中编写)并使其能够被JQuery代码操纵或呈现。 How can I do that? 我怎样才能做到这一点?

I am also trying to send JSON data back to the client but the JSON data gets rendered on the client side, instead of being handled by the JQuery code. 我也尝试将JSON数据发送回客户端,但JSON数据在客户端呈现,而不是由JQuery代码处理。

Here's the client side code that receives a JSON message after file upload 这是在文件上载后接收JSON消息的客户端代码

function sendFile() {

    $(new ID().setAsRoot().selectId()).append(
        "<form id=\"fileUploadForm\" accept-charset=\"utf-8\" method=\"post\" action=\"/upload\" enctype=\"multipart/form-data\"><input id = \"filename\" type=\"file\" name=\"userfile\" multiple=\"multiple\" /><button type=\"submit\"> Upload </button></form>");

    var $form = $("#fileUploadForm");
    alert("Started");
    $form.submit(function (e) {
        // perform client side validations if any

        this.ajaxSubmit({
            error: function () {
                alert("Error");
            },

            success: function (response) {
                var x = response.message;
                alert("Success  : " + x);
            }
        });

        // Important: stop event propagation
        return false;
    });
}

Here's the server side code for sending the response: 这是用于发送响应的服务器端代码:

respond: function respond(req, res, next) {
        console.log("Responding");
        var response = {
            result: 'success',
            upload: req.uploadLink,
            message: 'File uploaded!'
        };
        res.status(200).json(response);
        console.log("Response complete");
    },

Here's the JSON getting rendered on the screen: 这是在屏幕上呈现的JSON:

{
  "result": "success",
  "upload": "\\data\\tempFile4",
  "message": "File uploaded!"
}

to send JSON data or any data you can use, res.send({}) 发送JSON数据或您可以使用的任何数据,res.send({})

app.get('/filepath.json', function(req, res){
  var response = {
        result: 'success',
        upload: req.uploadLink,
        message: 'File uploaded!'
    };
  res.send(response)
});

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

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