【问题标题】:HTML form not sending data to node jsHTML表单不向节点js发送数据
【发布时间】:2020-08-01 12:59:13
【问题描述】:

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

我有一个 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>

和一个节点js文件

//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);
});

目录结构:

|
|-index.js
|-公开
|--index.html

在 post 路由中,req.body 为空,它会打印{}

【问题讨论】:

    标签: javascript html node.js express


    【解决方案1】:

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

    1. 从 npm 安装 cors

      npm install cors

    2. 为您的路由使用 CORS 中间件

    const cors = require('cors');
    .
    .
    .
    app.post('/action', cors(), (req, res) => {
       console.log(req.body)
       res.statusCode=200;
       res.end("thnx")
    });
    
    

    查看express official documentation了解更多信息

    【讨论】:

    • 这是因为我的目录结构我添加了有问题的目录结构
    • 不,只要在同一个主机上,这都不是问题。尝试了相同的结构,它工作正常。还可以考虑使用app.use(express.static('public')); 提供静态文件。
    猜你喜欢
    • 2018-10-09
    • 2016-07-19
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 2020-07-06
    • 2018-06-10
    • 1970-01-01
    • 2014-09-08
    相关资源
    最近更新 更多