2 回答
TA贡献1866条经验 获得超5个赞
抱歉耽搁了...我试图在代码沙箱上托管它...
你可以像这样制作你的节点端
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const path = require("path");
const app = express();
const router = express.Router();
const PORT = process.env.PORT || 5000;
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
router.get("/", function(req, res) {
res.sendFile(path.join(__dirname + "/index.html"));
});
router.post("/signup", (req, res) => {
console.log(req.body);
});
app.use(router);
app.listen(PORT, () => {
console.log(`Server started at PORT:${PORT}`);
});
并创建一个 HTML 文件,您将在其中使用 fetch API 使用 API
像这样的东西
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<form action="/signup" method="post">
<input
required
type="email"
name="email"
id="emailForm"
placeholder="Your Email"
/>
<input
type="password"
name="password"
id="passwordForm"
placeholder="Password"
/>
<input type="submit" name="" id="submit" value="Signup!" />
</form>
<script>
const emailForm = document.querySelector('#emailForm');
const passwordForm = document.querySelector('#passwordForm');
const submit = document.querySelector('#submit');
const submitFetch = (url, data) => {
fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
referrer: 'no-referrer',
body: JSON.stringify(data)
}).then(response => response.json());
};
submit.addEventListener('click', e => {
e.preventDefault();
const data = {
email: emailForm.value,
password: emailForm.value
};
submitFetch('http://localhost:5000/signup', data);
});
</script>
</body>
</html>
如果您想现场观看...我将其托管在代码沙箱上
https://codesandbox.io/s/lucid-cannon-x1wu1
TA贡献1831条经验 获得超9个赞
您似乎没有向客户返回任何响应。您可以纠正的一种方法是使用 express 提供的 res 对象中的 send 函数。
app.post('/signup', function(req, res, next) {
console.log(req.body);
res.send('Hello World') // this can also take an object as response. res.send({ msg: 'hello world' })
});
重新调整这条线也可能会有所帮助 ok comment out this line app.use(function(req, res, next) { next(createError(404)); });
希望这可以帮助。
添加回答
举报