Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 403禁止的expressjs后端_Node.js_Express - Fatal编程技术网

Node.js 403禁止的expressjs后端

Node.js 403禁止的expressjs后端,node.js,express,Node.js,Express,我检查了网站上的令牌,我得到了无效的签名,所以我猜问题出在哪里,但我忽略了如何修复它 我搜索了这个错误,我发现:收到403响应是服务器告诉你的,“很抱歉。我知道你是谁——我相信你说的是谁——但你没有访问此资源的权限。如果你向系统管理员询问,也许你会获得权限。但在你的困境改变之前,请不要再打扰我。” 前端的API GET函数: GET http://localhost:5000/booksIdea/show 403 (Forbidden) 后端app.js import axios from

我检查了网站上的令牌,我得到了无效的签名,所以我猜问题出在哪里,但我忽略了如何修复它 我搜索了这个错误,我发现:收到403响应是服务器告诉你的,“很抱歉。我知道你是谁——我相信你说的是谁——但你没有访问此资源的权限。如果你向系统管理员询问,也许你会获得权限。但在你的困境改变之前,请不要再打扰我。”

前端的API GET函数:

GET http://localhost:5000/booksIdea/show 403 (Forbidden)
后端app.js

import axios from 'axios'

export const ShowBooks = () => {
    let token = localStorage.getItem("usertoken")

    return axios.get("http://localhost:5000/booksIdea/show", {
        headers: {
          Authorization: `Bearer ${token}`, //here remove + in template litereal
        },
      })
      .then(res => {
          console.log("Success")
      })
      .catch(error => {
        console.log(error)
      })

}
这里是路线

const express = require('express')
var cookieParser = require('cookie-parser')
const app = express()
var cors = require('cors')
var bodyParser = require('body-parser')
const port = 5000
const routes = require("./routes");
const con = require('./db')
var cors = require('cors')
app.use(cors())
// database connect 

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

  //cookie 
  app.use(cookieParser())
//routes
// support parsing of application/json type post data
app.use(bodyParser.json());

//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));

app.use("/", routes);


app.listen(port, () => console.log(`Example app listening on port ${port}!`))
授权控制器


如何修复此错误?提前感谢您的帮助检查您的localstorage
localstorage.getItem(“usertoken”)

您的代币可以是:

  • 缺失或未定义

  • 不正确的标记-可能是输入错误


  • 请发布您的路线其他路线(如
    /booksIdea/:id'
    /booksIdea/addbook
    )是否正常工作或返回相同的错误?对于邮递员,它正常工作,但在react中我收到了此问题。我添加了一个答案,让我知道您是否可以为authController添加代码。验证?因此我对应用程序进行注释。使用(cors()),我从源站“”访问“”处的XMLHttpRequest已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许源站”标头。感谢尝试。我已更新了我的答案。它肯定不是CORS()那么问题就来了。跟踪令牌并确保它不是空的/未定义的吗?添加引号:将
    授权
    替换为
    授权
    仍然存在问题:/
    var express = require('express')
    var router = express.Router()
    var Controller = require('./controller')
    var authController = require('./authController')
    var BooksIdeaController = require('./BooksIdeaController')
    router.post('/register',Controller.register);
    router.post('/login',authController.login);
    router.post('/booksIdea/:id',authController.verify,BooksIdeaController.addComment)
    router.post('/booksIdea/addbook',authController.verify,BooksIdeaController.addBookIdea)
    router.get('/booksIdea/show',authController.verify,BooksIdeaController.showBookIdea)
    router.put('/booksIdea/edit/:id',authController.verify,BooksIdeaController.UpdateBookIdea)
    router.delete('/booksIdea/delete/:id',authController.verify,BooksIdeaController.DeleteBookIdea)
    module.exports = router;
    
    const con = require('./db');
    var bcrypt = require('bcrypt');
    let jwt = require('jsonwebtoken');
    const express = require('express')
    var cookieParser = require('cookie-parser')
    const app = express()
    module.exports.login=function(req,res){
        var username=req.body.name;
        var password=req.body.password;
        con.query('SELECT * FROM users WHERE username = ?',[username], function (error, results, fields) {
          if (error) {
              res.json({
                status:false,
                message:'there are some error with query'
                })
          }else{
            if(results.length >0){
              bcrypt.compare(password, results[0].password, function (err, result) {
                if (result == true) {
            jwt.sign({user:results},'configSecret',(err,token)=>{
              res.json({
                token:token
              })
    
    
            });
    
    
    
                //   res.json({
                //     status:true,
                //     message:'successfully authenticated'
                // })
                } else {
                  res.json({
                          status:false,
                          message:"username and password does not match"
                         });
                }
              });
            }
            else{
              res.json({
                  status:false,    
                message:"username does not exits"
              });
            }
          }
        });
    }
    
    module.exports.home=function(req,res){
    res.send('hello');
    }
    //////
    // if(password==results[0].password){
    
      // }else{
      //    
      // }
      module.exports.verify = function verifyToken(req, res, next) {
        // Get auth header value
        const bearerHeader = req.headers['authorization'];
        // Check if bearer is undefined
        if(typeof bearerHeader !== 'undefined') {
          // Split at the space
          const bearer = bearerHeader.split(' ');
          // Get token from array
          const bearerToken = bearer[1];
          // Set the token
          req.token = bearerToken;
          // Next middleware
          next();
        } else {
          // Forbidden
          res.sendStatus(403);
        }
    
      }