jquery - AJAX post 请求后将数据返回给客户端?

标签 jquery ajax node.js google-chrome-extension

我正在尝试从我的 chrome 扩展程序发送 POST 请求到我的 node.js 服务器,然后让服务器将 JS 文件发送回我的扩展程序。最好的方法是什么?

目前尝试过这个:

服务器.js

function sendJSfile(req, res) {
    var body = req.body.apples
    console.log(body)

    if (body.length >= 3) {
        console.log("Long!")
    } else{
        console.log("Short!")
        res.writeHead(200, {"Content-Type": "text/javascript"});
        fs.createReadStream("./manual.js").pipe(res);
    }
}

客户端.js

     request("https://61d6b1ac.ngrok.io/api/panels/hitme", "post", "JSON", {apples})
    .done(function(res){
      console.log(res)

    })
  })

 function request(url, method, dataType, data){
  return $.ajax({
  url: url,
  method: method,
  dataType: dataType,
  data: data
   })
  }

最佳答案

我注意到的一件事是,您已编写 AJAX 来从服务器接收 JSON 数据,但从服务器发送内容类型为 javascript,这可能不起作用。

另外,根据您的问题,您希望将 js 文件发送回客户端。有 3 种方法可以做到这一点 -

  1. 您可以将 JS 文件的内容作为字符串发送,然后在 ajax 成功响应中执行。这是不好的方法。

  2. 您可以从 NodeJS 服务器发送 JS 文件的公共(public) url,然后使用 <script>您可以在 JS 中下载相同的标签。

  3. 您还可以使用$.getScript如果您知道客户端的公共(public) JS url。

就您上面的服务器代码而言,您可以按如下方式从服务器返回 JS 内容 -

    function sendJSfile(req, res) {
    var body = req.body.apples
    console.log(body)

    if (body.length >= 3) {
    console.log("Long!")
    // here you will need to send error or something to the request
     res.send();
    } else{
    console.log("Short!")
    res.writeHead(200, {"Content-Type": "text/javascript"});
    //fs.createReadStream("./manual.js").pipe(res);
    // if you want to send manual.js content, then this can be sent as  following
    var readStream = fs.createReadStream("./manual.js");

     readStream.on('open', function () {
     // This just pipes the read stream to the response object (which goes to the client)
          readStream.pipe(res);
     });

    // This catches any errors that happen while creating the readable stream 
       readStream.on('error', function(err) {
    res.end(err);
    });
    }
    }

关于jquery - AJAX post 请求后将数据返回给客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33845018/

相关文章:

javascript - lightSlider 销毁并重建只需运行一次

javascript - .click 函数中的 $.get

javascript - 使用 webRTC 获取屏幕列表并选择要在 Electron 中记录的屏幕

javascript - 在 for 循环中链接 Promise 的最佳方式是什么?

jquery 表单验证无法使用页面中的选项卡

javascript - 嵌套jquery有大量数据

Jquery:在某些元素上运行方法,但不在其他元素上运行方法

javascript - 根据文本字段中的用户输入隐藏/显示复选框

javascript - 关闭弹出模式

node.js - 创建一个支持回调和 promise 的 Mongoose 插件