我刚刚开始学习Express和MySQL,然后按照Traversy Media(https://www.youtube.com/watch?v=EN6Dx22cPRI)上的简单教程创建了一个CRUD风格的应用程序。
这是我编写的简单应用程序:
const express = require('express');
const mysql = require('mysql');
const auth = require('./auth.json');
// Create connection
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: auth.password,
database: auth.database
});
// Connect
db.connect((err) => {
if (err) {
throw err;
} else {
console.log('MySQL Connected...');
}
});
const app = express();
// Insert post 1
app.post('/addpost1', (req, res) => {
let post = {name: 'Xbox One', price: 450};
let sql = 'INSERT INTO products SET ?';
db.query(sql, post, (err, result) => {
if (err) throw err;
console.log(result);
res.send('Post added...');
});
});
// Select posts
app.get('/selectposts', (req, res) => {
let sql = 'SELECT * FROM products';
db.query(sql, (err, result) => {
if (err) throw err;
console.log(result);
res.send(result);
});
});
// Update post
app.get('/updatepost/:id', (req, res) => {
let updatedPrice = 560;
let sql = 'UPDATE products SET price =' + updatedPrice + ' WHERE
product_id =' + req.params.id;
db.query(sql, (err, result) => {
if (err) throw err;
console.log(result);
res.send('Post updated...');
})
});
// Delete post
app.get('/deletepost/:id', (req, res) => {
let sql = 'DELETE FROM products WHERE product_id =' + req.params.id;
let query = db.query(sql, (err, result) => {
if (err) throw err;
console.log(result);
res.send('Post deleted...');
});
});
app.listen('3000', () => {
console.log('Server started on port 3000');
});
除第一个帖子请求(插入帖子1)外,其他所有东西都工作正常,如果我在浏览器中导航到/ addpost1,则会收到错误:“无法获取/ addpost1”。
这是为什么?我虽然应该在将一些数据发布/插入数据库中时使用app.post,但是却显示“无法获取”?如果我将其更改为app.get,它将可以正常工作并将帖子添加到数据库中,但是为什么呢?我是Web开发的新手,如果这非常明显,请抱歉。谢谢。