How to resolve Cors error in Node

Asked

Viewed 47 times

0

I did my backend with Node/express normally and tested all routes in India and everything took place normally at the front(vuejs) made requests via Xios, all routes also worked, except the authentication route of token, someone knows why?

Error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3333/api/v1/authorization. (Reason: Multiple CORS header ‘Access-Control-Allow-Origin’ not allowed).

Backend app:

const express = require('express');
const cors = require('cors');

const app = express()


const authRoutes = require('./routes/auth.routes');

app.use(cors('*'));

app.use(authRoutes);

Route:

const express = require('express');
const router = express.Router();
const verifyToken = require('../middlewares/token.middlewares');

router.get('/api/v1/authorization', verifyToken, (req, res) => {
  res.status(100).json({
    sucess: true,
    message: 'Token is valid',
    decoded: req.decoded,
  });
});

module.exports = router;

Middleware:

const jwt = require('jsonwebtoken');

const verifyToken = (req, res, next) => {
  try {
    const headerAuth = req.headers.authorization;
    if (!headerAuth) {
      return res
        .status(401)
        .json({ sucess: false, message: 'No token provided' });
    }
    const [, token] = headerAuth.split(' ');
    jwt.verify(token, process.env.SECRET, (err, decoded) => {
      if (err) {
        return res.status(500).json({
          sucess: false,
          message: 'Failed to authenticate token',
        });
      }

      req.decoded = decoded;
      next();
    });
  } catch (err) {
    res.json({ sucess: false, error: err });
  }
};

module.exports = verifyToken;

In frontend I call him so:

import api from './api';
// api é um arquivo de configuração do axios, somente, e provavelmente está correto pois uso ele em outras rotas normalmente
async function authorization(token){
    const btoken = `Bearer ${token}`;
    api.get('/authorization', {
        headers: {
            Authorization: btoken
        }
    })
    .then((response) => {
        return response;
    }).catch((err) => {
        return err;
    })
}

export default authorization;

Does anyone have any idea what it might be?

  • I see you’re calling req.headers.authorization and is setting Autorization, will it be if it’s not that? Case sensitive?

  • thanks for the help, but the mistake was not there, I discovered that there in the middleware I was sending the status 100 instead of 200, I just needed to change and it worked out

  • Nice... I’m glad it worked out

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.