Axios对MySql的GET请求产生错误404

nfg76nw0  于 2023-02-15  发布在  Mysql
关注(0)|答案(1)|浏览(104)

我正在尝试将我的CRUD应用程序连接到MySQL(react,nodeJS,express)。之前它连接到JSON服务器,一切正常。GET请求对所有数据库项目都很好,我也可以通过应用程序将新项目发布到数据库,但是,当我尝试访问单个项目的页面(例如http://localhost:5173/posts/4)时,我收到404未找到错误。

import express from "express";
import { Request, Response } from "express";
import bodyparser from "body-parser";
import cors from "cors";

const app = express();

app.use(bodyparser.json());
app.use(cors({ origin: "*" }));

app.get("/", (req: Request, res: Response) => {
  res.send("Application works!");
});

app.listen(3004, () => {
  console.log("Application started on port 3004!");
});

const mysql = require('mysql2');
const pool = mysql.createConnection({
    host: 'localhost',
    port: '3306',
    user: 'root',
    password: '123456',
    database: 'myBlog',
});

pool.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
});

app.get('/posts', (req: Request, res: Response) => {
  pool.connect(function (err) {
      if (err) throw err;
      pool.query('SELECT * FROM blog', function (err, result, fields) {
          if (err) throw err;
          res.send(result);
          console.log(result);
          });
  });
});

app.post('/posts', (req: Request, res: Response) => {
  const title = req.body.title
  const content = req.body.content
  const image = req.body.image
  const sqlInsert = 'INSERT INTO blog (title, content, image) VALUES (?, ?, ?);'
  pool.query(sqlInsert, [title, content, image], (err, result) => {
  })
})

app.get('/posts/:id', (req: Request, res: Response) => {
  const id = req.params.id
  const sqlInsert = "SELECT * FROM blog WHERE id = ?;"
  pool.query(sqlInsert, id, (err, result) => {
    if (err) throw err;
    res.send(result);
    console.log(result);
  })
})

这里是前端部分(当我使用JSON服务器时没有问题):

import { useParams, useNavigate } from "react-router-dom";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { PostCards } from "../Posts/Posts";
import React, { useState } from 'react'
import axios from 'axios'
import { AllPosts } from '../Posts/Posts'
import style from '../OnePost/OnePost.module.scss'

const getOnePost = async (id: string) => {
    const { data } = await axios.get(`http://localhost:3004/posts/${id}`)
    return data
}

const OnePost = () => {
    const [updateTitle, setUpdateTitle] = useState('')
    const [updateText, setUpdateText] = useState('')
    const [updateImage, setUpdateImage] = useState('')
    const [showEdit, setShowEdit] = useState(true)

    const onEdit = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
        e.preventDefault()
        setShowEdit(false)
    }

    const { id } = useParams()
    const navigate = useNavigate()
    const { data, isLoading } = useQuery<PostCards>(['onePost'], () => getOnePost(id!))

    
    if (isLoading) {
        return <h1>Loading...</h1>
    }

    if (!data) {
        navigate('/')

        return null
    }

    const {title, content, image} = data

    const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault()
        setShowEdit(true)
        axios.put(`http://localhost:3004/posts/${id}`, {
          title: updateTitle,
          content: updateText,
          image: updateImage
        }).then(({ data }) => {
            axios.get(`http://localhost:3004/posts/${id}`)
          });
    }

    return (
        <div className={style.container}>
            <img src={image} width='600' height='400'></img>
            <h1 className={style.title}>{title}</h1>
            <p className={style.text}>{content}</p>
            <button className={style.button} onClick={onEdit}>EDIT</button>
            <form onSubmit={onSubmit} className={`editHidden ${!showEdit && 'editActive'}`}>
                <label>
                    Image <br /> <br />
                    <input
                     className={style.field}
                     required
                     defaultValue={image}
                     onChange={(e: React.ChangeEvent<HTMLInputElement>) => setUpdateImage(e.target.value)}
                     />
                </label>
                <label>
                    Title <br /><br />
                    <input
                    className={style.field}
                    required
                    defaultValue={title}
                    onChange={(e: React.ChangeEvent<HTMLInputElement>) => setUpdateTitle(e.target.value)}/>
                </label>
                <label>
                    Text <br /><br />
                    <textarea
                    className={style.textarea}
                    required
                    defaultValue={content}
                    onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setUpdateText(e.target.value)}
                    >
                    </textarea>
                </label>
                <button className={style.button}>UPDATE</button>
            </form>   
        </div>
      
    );
  };
  

  export default OnePost

也许问题是端口不匹配?但在这种情况下,为什么GET所有帖子和POST请求都能工作呢?

brccelvz

brccelvz1#

尝试打印“www.example.com”的类型req.params.id,它需要与您的id列类型相同。将其转换为int时应:

app.get('/posts/:id', (req: Request, res: Response) => {
  const id = parseInt(req.params.id)
  const sqlInsert = "SELECT * FROM blog WHERE id = ?;"
  pool.query(sqlInsert, id, (err, result) => {
    if (err) throw err;
    res.send(result);
    console.log(result);
  })
})

相关问题