无法检索Express JS中由表单标签发布的文本数据

时间:2019-06-14 00:05:08

标签: javascript html express google-chrome-extension

我正在开发一个简单的管道,当用户在chrome页面中突出显示一个文本块并单击扩展名时,它将在chrome扩展名<iframe>中定义的popup.js中显示突出显示的文本并发送在Express.js中运行的服务器上突出显示的文本。

当前状态是运行popup.js的popup.html,popup.js将highlighted text记入document中。到目前为止,效果很好。

但是,每当我击中node app.js时,undefined的运行终端会一直显示chrome extension favicon。我希望突出显示的文本显示在终端日志中。

此不当行为的可能原因是什么?

popup.html

<html>
    <head>
        <meta charset="UTF-8">
        <style>
            body {
                width: 400px;
                height: 500px;
            }
            iframe {
                width: 400px;
                height: 500px;
            }
        </style>
    </head>
    <body>

        <iframe frameborder="1"></iframe> <!--'1' for border on/ '0' for border off-->

        <script type="text/javascript" src="popup.js"></script>

    </body>
</html>

popup.js

chrome.tabs.executeScript( {
    code: "window.getSelection().toString();"
}, function(selection) {

    document.write(selection[0]);

    var text =
        '<form action="http://localhost:8080/example" method="post" id="hlgt_form">' +
        '<input type="hidden" id = "hlgt" name = "hlgt" value= ""> ' +
        '</form>';

    document.write(text);

    document.getElementById('hlgt').value = selection[0];
    // it stores highlights into value of <input>

    document.getElementById('hlgt_form').submit();
});

app.js (由节点app.js运行)

const express = require('express');
const app = express();

app.use(express.json());

const port = 8080;

app.listen(port, () => {
    console.log(`Server running on port: ${port}`);
});

app.post('/example', (req, res) => {
    console.log(`${req.body.name.hlgt}`);
});

2 个答案:

答案 0 :(得分:1)

我认为问题出在您的Express应用中。您似乎并没有使用body-parser中间件来实际获取请求中的HTTP POST数据,即使您这样做了,也可以将该信息引用为req.body.hlgt,而无需使用.name。 / p>

尝试这样的事情:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));

const port = 8080;

app.listen(port, () => {
    console.log(`Server running on port: ${port}`);
});

app.post('/example', (req, res) => {
    console.log(`${req.body.hlgt}`);
});

答案 1 :(得分:0)

只写这两行

app.use(bodyParser.urlencoded({ extended: false }));

app.use(bodyParser.json({limit:"5MB"}));