简体   繁体   English

从 Nodejs express 应用程序发布到 MySQL 数据库返回 404

[英]Posting from Nodejs express app to MySQL database returns 404

I am trying post to MySQL database but getting a 404 error.我正在尝试发布到 MySQL 数据库但收到 404 错误。 I have gone through numerous posts here but all the accepted answers didn't work for me.我在这里浏览了许多帖子,但所有接受的答案都对我不起作用。 I just can't understand what I'm doing wrong.我只是不明白我做错了什么。

When I use a GET request, this code works well:当我使用 GET 请求时,此代码运行良好:

router.get("/", (req, res) => {
  let sql = "SELECT shop_name_en, shop_id FROM mst_shop";
  let query = db.query(sql, (err, results) => {
    if(err) throw err;
    res.send({ results });
  });
});

However, when I try to use POST, it returns a 404 error in console.但是,当我尝试使用 POST 时,它会在控制台中返回 404 错误。

router.post("/", (req, res) => {
  let sql = "UPDATE mst_shop SET review_count = 5 WHERE shop_id = 1";
  let query = db.query(sql, (err, results) => {
    if(err) throw err;
    console.log("1 record inserted");
    res.send(results);
  })
});

I don't understand what I'm doing wrong.我不明白我做错了什么。 I tested the MySQL code and it works well when I do it through myphpadmin.我测试了 MySQL 代码,当我通过 myphpadmin 执行此操作时,它运行良好。 I am relatively new to this so I feel like I'm missing something very obvious.我对此比较陌生,所以我觉得我错过了一些非常明显的东西。 Here is my code in context:这是我在上下文中的代码:

var express = require("express");
var mysql = require("mysql");
var router = express.Router();

const db = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'booo',
});

db.connect((err) => {
  if(err) throw err;
  console.log("MySQL database is connected. Noicey!")
});

router.post("/", (req, res) => {
  let sql = "UPDATE mst_shop SET review_count = 5 WHERE shop_id = 1";
  let query = db.query(sql, (err, results) => {
    if(err) throw err;
    console.log("1 record inserted");
    res.send(results);
  })
});

module.exports = router;

As I mentioned earlier, a get request works well, but not the post.正如我之前提到的,get 请求效果很好,但 post 却不行。

Alright, I have understood what was the problem after lots of trial and error.好吧,经过大量的反复试验,我明白了问题所在。 Seems that I had to use the same .get method instead of .post method, so the correct way for my code to work was simply changing post to get like so:似乎我必须使用相同的.get方法而不是.post方法,所以我的代码工作的正确方法是简单地将 post 更改为如下所示:

router.get("/", (req, res) => {
  let sql = "UPDATE mst_shop SET review_count = 5 WHERE shop_id = 1";
  let query = db.query(sql, (err, results) => {
    if(err) throw err;
    console.log("1 record inserted");
    res.send(results);
  })
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM