我想在调用某个函数时从页面收集数据,然后将数据发送到我的数据库。我正在使用 Expressjs 和 Nodejs。
Fetch 的功能:
function saveShapeData() {
const shapesData = [];
$(".shape").each(function() {
const shapeId = $(this).attr("id");
const shapeData = {
id: shapeId,
imgElement: $(this).find("img").attr("src"),
items: $(this).data("info") ? $(this).data("info").items : [],
css: $(this).attr("style")
};
shapesData.push(shapeData);
});
fetch("/api/shapes", {
method: "POST",
body: JSON.stringify(shapesData),
headers: {
"Content-Type": "application/json"
}
})}
路由器:
router.get("/shapes", loggedIn, (req, res) => {
if(req.user){
console.log("saedfe " + req.user.shapes);
res.sendFile("shapes.html", { root: "./public/" });
}
else{
res.render("index", {status:"no", user: "nothing"});
}
})
控制器:
const db = require('../routes/db-config.js');
const jwt = require('jsonwebtoken');
const shapes = async (req, res, next) => {
const { shapesData } = req.body;
if (!req.cookies.userRegistered) return next();
try{
const decoder = jwt.verify(req.cookies.userRegistered, process.env.JWT_SECRET);
db.query('INSERT INTO users VALUES (?) WHERE id = ?', [shapesData, decoder.id], (err, result) => {
if(err) return next();
return next();
})
} catch (err){
if(err) return next()
}
}
module.exports = shapes;
我有注册和登录页面,它们可以使用几乎相同的结构化代码正常工作,但是这个返回错误:
POST http://localhost:5000/api/shapes/ 404 (Not Found)
我的 auth.js 看起来像这样,登录和注册页面的路由方式相同:
const express = require('express');
const register = require('./register')
const login = require('./login')
const shapes = require('./shapes')
const router = express.Router();
router.post("/register", register)
router.post("/login", login)
router.post("/shapes", shapes)
module.exports = router;
尝试删除“api” POST http://localhost:5000/api/shapes/ 在你展示的内容中,没有这样的路线