Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/477.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript HTML表单不向节点js发送数据_Javascript_Html_Node.js_Express - Fatal编程技术网

Javascript HTML表单不向节点js发送数据

Javascript HTML表单不向节点js发送数据,javascript,html,node.js,express,Javascript,Html,Node.js,Express,我试图实现一个html表单,它接受输入并将其发送到NodeJS服务器,但html表单没有向NodeJS发送任何数据。它发出请求,但不发送表单数据 我有一个index.html文件 <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Input Form</title> </head> <body> &l

我试图实现一个html表单,它接受输入并将其发送到NodeJS服务器,但html表单没有向NodeJS发送任何数据。它发出请求,但不发送表单数据

我有一个index.html文件

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Input Form</title>
</head>
<body>
    <h1>Send a message:</h1>
    <form action="http://localhost:3000/action" method="POST">
        <label for="data">Message:</label>
        <input type="text" id="data" placeholder="Enter your message" name="text"/>
        <input type="submit" value="Send message" />
    </form>
</body>
</html>
目录结构:

|
|-index.js
|-公共
|--index.html


在post路由中,req.body是空的,它打印{}

我尝试了完全相同的代码,它工作得非常好。它不适用于您的一个可能原因是html表单位于不同的主机上,默认情况下不允许跨源请求。要允许所有来源:

  • 从npm安装cors

    npm安装cors

  • 为您的路线使用CORS中间件


  • 检查更多信息

    这是因为我的目录结构吗?我在问题中添加了我的目录结构。不,只要它在同一个主机上,这就不会有问题。用同样的结构试过,效果很好。也可以考虑使用<代码> App.使用(Express,static(“公共”));<代码>用于提供静态文件。
    //Modules
    const fs = require ('fs');
    const express = require('express');
    const app = express();
    const bodyParser = require('body-parser');
    const http = require('http');
    const actionRoute=require('./routes/action')
    const server = http.createServer(app)
    app.use(express.urlencoded({ extended: true }))
    app.use(bodyParser.json())
    app.all('/',(req,res)=>{
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/html');
        res.end(fs.readFileSync('./public/index.html'))
    })
    const hostname = 'localhost';
    const port = 3000
    
    app.post('/action',(req,res)=>{
        console.log(req.body)
        res.statusCode=200;
        res.end("thnx")
    })
    
    
    server.listen(port , hostname,function(){
        console.log('Server running at http://'+hostname+':'+port);
    });
    
    const cors = require('cors');
    .
    .
    .
    app.post('/action', cors(), (req, res) => {
       console.log(req.body)
       res.statusCode=200;
       res.end("thnx")
    });