为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

汪汪一只猫 2022-12-18 16:02:59
我正在尝试实现一个 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文件//Modulesconst 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 = 3000app.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 为空,它打印{}
查看完整描述

1 回答

?
FFIVE

TA贡献1797条经验 获得超6个赞

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

  1. 从 npm 安装 cors

    npm 安装 cors

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

const cors = require('cors');

.

.

.

app.post('/action', cors(), (req, res) => {

   console.log(req.body)

   res.statusCode=200;

   res.end("thnx")

});


查看express 官方文档了解更多



查看完整回答
反对 回复 2022-12-18
  • 1 回答
  • 0 关注
  • 71 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信