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

我正在尝试实现一个 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

|-public

|--index.html


在发布路由中,req.body 为空,它打印{}


汪汪一只猫
浏览 72回答 1
1回答

FFIVE

我尝试了完全相同的代码并且它运行良好。它对您不起作用的一个可能原因是 html 表单位于不同的主机上,默认情况下不允许跨域请求。允许所有来源:从 npm 安装 corsnpm 安装 cors为您的路线使用 CORS 中间件const cors = require('cors');...app.post('/action', cors(), (req, res) => {&nbsp; &nbsp;console.log(req.body)&nbsp; &nbsp;res.statusCode=200;&nbsp; &nbsp;res.end("thnx")});查看express 官方文档了解更多
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript