创建新配方并将其添加到 table 'recipes' 时出现 401 错误

401 ERROR when creating new recipe and adding it to the table 'recipes'

尝试创建新食谱并将其添加到数据库时,我收到 401 未经授权的错误消息。

可能与以下内容有关...:[=​​20=]

Profile.js(注册用户可以看到他们所有的食谱,可以创建、更新和删除食谱)是一条受保护的路线,只有注册用户才能看到此页面上的内容。 当有人注册或登录时,他们将被重定向到 Profile.js。

问题:任何登录或注册的人都可以看到所有食谱 - 虽然我创建了一个外键,将 recipe_user (user_id) 从食谱链接到用户的 ID。

我相信因为这不能正常工作 - 创建也不能工作。

我尝试将 console.log 放在不同的地方以确定哪里出错了,我尝试了不同的值 - 没有任何效果...

在此处查找所有相关代码: https://gist.github.com/MisterSemaan/07d7cf52b0069d2ea89b29f608c2b976

以下是我的代码中最相关的部分:

__In Profile.js 获取 -->

  componentDidMount() {
    const jwt = localStorage.getItem('jwt')
    console.log(jwt)
    if (jwt) {
      axios({
        method: 'get',
        url: 'http://localhost:4000/api/recipes',
        headers: {
          'Authorization': 'Bearer ' + jwt
        }
      }).then((response) => {
        console.log(response)
        this.setState({data: response.data.recipes})
      })
    }
  }

创建 -->

handleClick(event){
   const jwt = localStorage.getItem('jwt')
   console.log(jwt)
   axios({
     method: 'post',
     data: {
      name: this.state.recipe_name,
      author: this.state.recipe_author,
      meal: this.state.recipe_meal,
      description: this.state.recipe_description,
      ingredients: this.state.recipe_ingredients,
      preparation: this.state.recipe_preparation
     },
     url: 'http://localhost:4000/api/recipe',
     headers: {
       'Authorization': 'Bearer ' + jwt
     }
   }).then((response) => {
     console.log(response)
     this.setState({ recipe: response.data.recipes });
   }).catch((error, res) => {
    if(error.response.status === 401) {
       console.log("Error:", error);
       alert("Failed")
     }
   })
 }

渲染 -->

render(){
    return (
    <div>
      <div className="newRecipe">
        <TextField helperText="Enter the name of your recipe" label="name" onChange = {(event) => this.setState({name: data.recipe_name})}/>
        <br/>
        <TextField helperText="Enter your name" label="Author" onChange = {(event) => this.setState({author: data.recipe_author})}/>
        <br/>
        <TextField helperText="Enter the mealtype" label="meal" onChange = {(event) => this.setState({meal: data.recipe_meal})}/>
        <br/>
        <TextField helperText="Enter a short description of your recipe" label="description" onChange = {(event) => this.setState({description: data.recipe_description})}/>
        <br/>
        <TextField helperText="Enter the ingredients" label="ingredients" onChange = {(event) => this.setState({ingredients: data.recipe_ingredients})}/>
        <br/>
        <TextField helperText="Enter the preparation method" label="preparation" onChange = {(event) => this.setState({preparation: data.recipe_preparation})}/>
        <br/>
      </div>
      <Button color="secondary" onClick={(event) => this.handleClick(event)}>Submit Recipe</Button>
      <div className="RecipeCard">
        {
          this.state.data && this.state.data.map((data, key) => {
            return <RecipeCard name={data.recipe_name} author={data.recipe_author} meal={data.recipe_meal} description={data.recipe_description} ingredients={data.recipe_ingredients} preparation={data.recipe_preparation}/>
          })
        }
      </div>
    </div>
    );
  }

__In index.js

// 配置文件路径 - 受保护 api.get('/recipes', passport.authenticate('jwt', {session: false}), (req, res) => { db.query('SELECT * FROM recipes', (err, 行数) => { res.json({食谱:行数}); }) });

// Profile ROUTE - PROTECTED
api.get('/recipes', (req, res) => {
        const id = req.query.user_id;
        console.log(req.query)
        db.query('SELECT * FROM recipes WHERE user_id = ?', [user_id] , (err, rows) => {
            res.json({recipes: rows});
        })
});

// Profile CREATE ROUTE - PROTECTED
api.post('/recipe', passport.authenticate('jwt', {session: false}), (req, res) => {
        const recipe = {
            name: req.body.recipe_name,
            author: req.body.recipe_author,
            meal: req.body.recipe_meal,
            description: req.body.recipe_description,
            ingredients: req.body.recipe_ingredients,
            preparation: req.body.recipe_preparation
        }
        db.query('INSERT INTO recipes SET ?', recipe, (err, results) => {
            if (err) {
                res.status(500)
                return;
            }
            db.query('SELECT * FROM recipes', (err, rows) => {
                if (err) {
                    res.status(500)
                    return;
                }
                res.json({recipes: rows});
            })
        })
});

__Inindex.jsjwt

var jwtOptions = {}
jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
jwtOptions.secretOrKey = config.secret;
passport.use(new Strategy(jwtOptions, function(jwt_payload, next) {
    console.log('payload received', jwt_payload);
    db.query('SELECT * FROM users WHERE email = ?', [jwt_payload.email], (err, rows) => {
        let user = null
        if(rows && rows[0]){
            user = rows[0]
        }
        if (user) {
            next(null, user);
        } else {
            next(null, false);
        }
    })
}));
app.use(passport.initialize());

__In init.sql

食谱table-->

CREATE TABLE `recipes` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(10) unsigned NOT NULL,
  `recipe_image` int(11) DEFAULT NULL,
  `recipe_name` varchar(100) NOT NULL DEFAULT '',
  `recipe_meal` varchar(100) NOT NULL DEFAULT '',
  `recipe_author` varchar(100) NOT NULL DEFAULT '',
  `recipe_description` varchar(100) NOT NULL DEFAULT '',
  `recipe_ingredients` varchar(200) NOT NULL DEFAULT '',
  `recipe_preparation` varchar(400) NOT NULL DEFAULT '',
  `recipe_complete` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `recipe_user` (`user_id`),
  CONSTRAINT `recipe_user` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

用户table-->

CREATE TABLE `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` varchar(300) CHARACTER SET utf8mb4 NOT NULL DEFAULT '',
  `email` varchar(300) CHARACTER SET utf8mb4 NOT NULL DEFAULT '',
  `password` varchar(300) CHARACTER SET utf8mb4 NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

我希望我能解释它为什么有效,但我对 react.js 不是很了解。 所以这就是我所做的更改:

__In Profile.js,所有文本字段

发件人:: data.recipe_name

收件人:: event.target.value

__InProfile.js,处理点击数据

发件人:: 姓名:this.state.recipe_name,

收件人:: 姓名:this.state.name,

__In Profile.js, this.state

发件人:: 数据:[]

收件人:: 名称:'',
作者:'',
膳食:'',
描述:'',
成分:'',
准备:''

__In Profile.js, this.setState(我还不是100%正确)

发件人:: this.setState({ 食谱: response.data.recipes });

收件人:: this.setState({ 食谱: response.data.recipe });

我想是这样吗?如果我找到任何其他修复程序,我会保持更新:) 干杯