[英]How to send plain text from Javascript to NodeJS server
我正在使用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();
});
您可以嘗試將請求的內容類型更改為使用Content-Type: text/plain
如下所示:
xhttp.setRequestHeader("Content-type","text/plain");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.