我正在尝试从我的 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 种方法可以做到这一点 -
您可以将 JS 文件的内容作为字符串发送,然后在 ajax 成功响应中执行。这是不好的方法。
您可以从 NodeJS 服务器发送 JS 文件的公共(public) url,然后使用
<script>
您可以在 JS 中下载相同的标签。您还可以使用
$.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/