【问题标题】:How to send plain text from Javascript to NodeJS server如何将纯文本从 Javascript 发送到 NodeJS 服务器
【发布时间】: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


    【解决方案1】:

    您可以尝试将请求的内容类型更改为使用Content-Type: text/plain,如下所示:

     xhttp.setRequestHeader("Content-type","text/plain");
    

    【讨论】:

    • 我做了,但是服务器什么也没收到,我知道为什么
    • 您能否发布一个您在服务器上使用的代码示例?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-27
    • 2017-12-15
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    相关资源
    最近更新 更多