【发布时间】:2019-12-05 07:16:36
【问题描述】:
我正在使用 ExpressJS、Pug 和 ACE 作为编辑器构建在线编译器。我的想法是让用户在编辑器中键入他们的代码,将代码发送回服务器并将其保存到一个 txt 文件中,然后使用 ChildProcess 在那里编译代码并将输出返回给用户。
这是我面临的问题:
我想要一个向服务器发送 POST 请求的运行按钮,包括用户键入的代码,这是我目前的实现
script.
console.log('client-side script running :D');
const button = document.getElementById('runbutton');
button.addEventListener('click',function(e) {
const code = editor.getValue();
var xhttp = new XMLHttpRequest();
xhttp.open("POST","/run",true);
xhttp.setRequestHeader("Content-type","application/x-www-
form-urlencoded");
xhttp.send(code);
console.log(code);
});
顺便说一句,我正在使用 AJAX 来避免刷新页面。但是这里的问题是,当服务器收到代码时,由于 JSON 格式,它通常会比实际代码更多或更少的字符,所以我无法正确保存和编译代码。如何将纯文本格式的原始代码从客户端发送到服务器?
这里是我使用的服务器端代码
app.post('/run',(req,res) => {
console.log('Server route running');
const code = req.body; // code => still an object not yet a string
const codePath = path.join(__dirname,"public","CODE","code.txt"); // PROJECT/public/CODE/code.txt is created
const stream = fs.createWriteStream(codePath); // create a write stream
stream.write(JSON.stringify(code)); // save the stringify object
stream.end();
console.log(code);
res.end();
});
here is the different between the client code and server received code
【问题讨论】:
标签: javascript node.js ajax express pug