我的主要目標是使用 Node.js 創建一個 RestAPI 并在小型 HTML 應用程式中對其進行測驗。
我的老師通過一個示例幫助我們創建了 RestAPI,我能夠將其調整到我自己的 MySQL 資料庫中,并且我已經使用 Visual Studio Code 上的 Thunder Client 擴展測驗了 API 的每個端點,它作業正常。
但是我在測驗 html 應用程式時遇到問題。我正在嘗試使用表單發送一些資料,但是當我提交它時,它不會保存我放入表單的任何資料,而是將空值插入所有列。我知道端點是正確的,因為它真正連接到正確的函式和表,并將新的資料行插入到表中。
這是我的 HTML 表單
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Header</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<h1 id="teste"> Adicionar um Videojogo</h1>
<form action=" http://localhost:3000/api/videogames" method="post" enctype="multipart/form-data" >
<div class="form-item col" id="form_">
<input type="text" name= "nome" id="nome" placeholder="Nome" required= "required">
</div>
<div class="form-item" id="form_">
<input type="text" name= "produtora" id="produtora" placeholder="Produtora" required= "required">
</div>
<div class="form-item" id="form_">
<input type="text" name= "distribuidora" id="distribuidora" placeholder="Distribuidora" required= "required">
</div>
<div class="form-item" id="form_">
<input type="text" name= "ano" id="ano" placeholder="Ano" required= "required">
</div>
這是我的模型:
const sql = require("./db.js");
// construtor
const Videogame = function(videogame) {
this.nome = videogame.nome;
this.produtora = videogame.produtora;
this.distribuidora = videogame.distribuidora;
this.ano = videogame.ano;
this.id_genero= videogame.id_genero;
this.id_plataforma = videogame.id_plataforma;
}
Videogame.insert = (newVideogame, result) => {
sql.query('INSERT INTO videogame SET ?', newVideogame, (err, res) => {
if (err) {
console.log('error: ', err);
result(err, null);
return;
}
console.log("Videojogo inserido: ", { id: res.insertId, ...newVideogame });
result(null, { id: res.insertId, ...newVideogame});
});
}
我的控制器:
const Videogame = require("../models/videogame.model.js");
// Inserir um novo videojogo
exports.insert = (req, res) => {
// Validar a request
if (!req.body) {
res.status(400).send({
message: "O conteúdo do videojogo deve estar definido."
});
}
// Criar um "Videogame"
const videogame = new Videogame({
nome: req.body.nome,
produtora: req.body.produtora,
distribuidora: req.body.distribuidora,
ano: req.body.ano,
id_genero: req.body.id_genero,
id_plataforma: req.body.id_plataforma,
});
// Guardar "Videogame" na base de dados
Videogame.insert(videogame, (err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Ocorreu um erro ao inserir o videojogo..."
});
else res.send(data);
});
};
我的路線:
module.exports = app => {
const videogames = require("../controllers/videogame.controller.js");
var router = require("express").Router();
// Consultar todos os videojogos
router.get("/", videogames.selectAll);
// Consultar um videojogos pelo id
router.get("/:id", videogames.findById);
// Inserir um novo videojogo
router.post("/", videogames.insert);
// Atualizar um videojogo pelo id
router.put("/:id", videogames.update);
// Apagar um videojogo pelo id
router.delete("/:id", videogames.delete);
// Apagar todos os videojogos
router.delete("/", videogames.deleteAll);
app.use('/api/videogames', router);
};
我的服務器:
const express = require('express');
const cors = require('cors');
const app = express();
const PORT = process.env.PORT || 3000;
const corsOptions = {
origin: 'http://localhost'
};
app.use(cors(corsOptions));
// tratamento (parse) de pedidos de content-type - application/json
app.use(express.json());
// tratamento (parse) de pedidos de content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
/*// route de "entrada" - apenas para efeito de teste
app.get("/", (req, res) => {
res.json({ message: "Movies API . IPVC" });
});*/
// importa??o das videogames.routes com um argumento de inicializa??o
require('./app/routes/videogames.routes.js')(app);
// ativa??o do servidor, onde ser?o recebidos os pedidos, na porta definida
app.listen(PORT, () => {
console.log(`Servidor ativo na porta ${PORT}.`);
});
它連接到資料庫,但無論如何這里是資料庫連接
const mysql = require('mysql');
const DBConfig = require('../config/db.config.js');
// Criar conex?o à base de dados
const connection = mysql.createConnection({
host: DBConfig.DBSERVER,
user: DBConfig.DBUSER,
password: DBConfig.DBPASS,
database: DBConfig.DBNAME
});
// Abrir conex?o à base de dados
connection.connect(error => {
if (error) throw error;
console.log('Liga??o à base de dados estabelecida...');
});
module.exports = connection;
Here is the result that appear on the terminal, after i submit my form
Videojogo inserido: {
id: 14,
nome: undefined,
produtora: undefined,
distribuidora: undefined,
ano: undefined,
id_genero: undefined,
id_plataforma: undefined
}
It should save the data I from the form instead of undefined (I also have 2 radio buttons for id_genero and id_plataforma in my form, but I only put the other inputs here, because I don't think the problem is with the radio buttons, as if it were, it would assign the other input values in forms.)
uj5u.com熱心網友回復:
您正在使用,express.json()但您的表單資料不是 JSON 格式。
您可以express-formidable在您的應用檔案夾中使用 npm安裝
然后您需要使用它創建中間件,如下所示:
// in app.js
const formidableMiddleware = require('express-formidable');
//...
// Note that req.fields will be instead of req.body due to middleware
// used to handle json, forms, and uploading files
app.use(formidableMiddleware(
{
encoding: 'utf-8',
// means multi files (array of files) in one request
multiples: true,
}
));
您將需要app.use(express.json());用上面的代碼片段替換
您還可以從 github 上的 ExpressJS 存盤庫中查看多部分表單的示例
uj5u.com熱心網友回復:
我不知道你是如何設定服務器的,但你應該有一個中間件來決議傳入的資料。對于 HTML 表單資料,您需要使用以下內容app.use(express.urlencoded({ extended: false }));
您可以在此處閱讀以了解有關 express 內置中間件及其可選屬性的更多資訊。
還剛剛注意到您正在使用enctype="multipart/form-data",有什么原因嗎?您的表單看起來足夠基本,因此您應該能夠使用application/x-www-form-urlencoded默認表單,因此您無需指定它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/409927.html
標籤:
