html - 将html formdata发送到nodejs服务器时出错
问题描述
我在不同的端口上使用 html 表单和 nodejs 服务器。每次我尝试将数据从 HTML 表单发送到 nodejs 服务器时,我都会收到错误 405。但是,如果我在同一个端口上运行它们,一切正常。这是我的htmlform代码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="style.css">
<title>HTML FORM</title>
</head>
<body>
<div class="container">
<form action="http://localhost:3000/register" method="POST">
<div class="element">
<label for="name">NAME</label>
<input type="text" name="name" id="name" autocomplete="on">
</div>
<div class="element">
<label for="RollNo">ROLL NUMBER</label>
<input type="tel" name="RollNo" id="RollNo">
</div>
<div class="element">
<label for="contact">MOBILE</label>
<input type="tel" name="contact" id="contact">
</div>
<div class="element">
<label for="branch">BRANCH</label>
<select name="branch" id="branch">
<option value="CSE">CSE</option>
<option value="ME">ME</option>
<option value="ECE">ECE</option>
<option value="CIVIL">CIVIL</option>
</select>
</div>
<div class="element">
YEAR <br>
<input type="radio" name="Year" id="First">
<label for="First">1st Year</label><br>
<input type="radio" name="Year" id="Second">
<label for="Second">2nd Year</label><br>
<input type="radio" name="Year" id="Third">
<label for="Third">3rd Year</label><br>
<input type="radio" name="Year" id="Fourth">
<label for="Fourth">4th Year</label>
</div>
<div class="element">
<label for="DOB">Date of Birth</label>
<input type="date" name="DOB" id="DOB">
</div>
<div class="element">
<label for="email">Email</label>
<input type="email" name="email" id="email">
</div>
<div class="element">
<label for="password">Password</label>
<input type="password" name="password" id="password">
</div>
<!-- <div class="element">
<label for="image">Profile Photo</label>
<input type="file" name="image" id="image">
</div> -->
<div class="element">
<input type="submit" name="submit" id="submit">
<input type="reset" name="reset" id="reset"><br>
</div>
</form>
</div>
</body>
</html>
nodejs服务器的代码是这样的
const express=require('express');
const bodyParser=require('body-parser');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:false}))
app.post('/register',(req,res)=>{
console.log(req.body);
res.send(req.body);
})
app.listen(3000);
在此我的 HTML 表单在端口 8080 上运行,服务器在端口 3000 上运行。
解决方案
您是否尝试过查看 CORS NPM 包?
在 server.js 中:
const cors = require('cors')
app.use(cors());
推荐阅读
- python - pandas groupby + apply 的快速替代方案?
- visual-studio-code - Visual Code Prettier 如何在函数的开头保留空间
- firebase - 无法使用 oneSignal 发送消息,错误:字符串不是 List 类型的子类型
- php - 什么是 PHP Excel 工作表限制?如何切换 PHPExcel_IOFactory::createWriter?
- node.js - 使用 node JS v10 开发的 React 应用程序
- amazon-sqs - shoryuken 工作人员在失败后以最后一次重试间隔无限次重试
- java - 控制推土机映射的缓存
- python - 如何在数据框中找到其值为 True 的行?
- python-3.x - 以较低权限执行 python SubProcess
- android - org.gradle.api.InvalidUserCodeException:不支持在任务...完成之前查询提供者(java.util.Set)的映射值