No Access-Control-Allow-Origin header is present on the requested resource. - MEAN STACK

0

Hello! I need to pass a string to the node and I'm getting the following response from the browser console:

Failed to load http://localhost:3003/api/buscarCep: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4000' is therefore not allowed access. The response had HTTP status code 400.

The server is a node and is on the same machine that I'm testing. So it's all local. The CORS policies for my server follow below:

module.exports = function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE')
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization')
  next()
}

Non-angular factory:

(function () {
    angular.module('primeiraApp').factory('apiExterna', [
        '$http',
        'consts',
        ApiExterna
    ])

    function ApiExterna($http, consts) {

        function buscarCep(cep) {
            $http.post('http://localhost:3003/api/buscarCep', cep)
                .then(resp => {  
                    console.log(resp)          
                    return null
                }).catch(function (resp) {
                    console.log("erro")
                })
        }

        return { buscarCep }
    }
})()

The CEP parameter is received from a controller. So far so good, the problem happens from now on:

Backend routes:

const express = require('express')
const auth = require('./auth')

module.exports = function(server) {

  /*
   * Rotas protegidas por JWT
   */
  const protectedApi = express.Router()
  server.use('/api', protectedApi)

  protectedApi.use(auth)

  // rotas da API

  const alertasService = require('../api/alertas/alertasService')
  alertasService.register(protectedApi, '/alertas')

  const ApiService = require('../api/apiExterna/apiService')
  protectedApi.post('/buscarCep', ApiService.buscarCep)

}

"auth" is a module for application authentication.

Here I should receive the zip code:

const _ = require('lodash')
const fetch = require('node-fetch')

const buscarCep = (req, res, next) => {
    const cep = req.body.cep
}

module.exports = { buscarCep }

server.js node:

const port = 3003

const bodyParser = require('body-parser')
const express = require('express')
const server = express()
const allowCors = require('./cors')
const queryParser = require('express-query-int')

server.use(bodyParser.urlencoded({ extended: true }))
server.use(bodyParser.json())
server.use(allowCors)
server.use(queryParser())

server.listen(port, function() {
  console.log('BACKEND is running on port ${port}.')
}) 

module.exports = server

The strangest thing is that for example, everything on that "alerts" route works, but in that post there is no. Am I doing it wrong?

    
asked by anonymous 09.05.2018 / 02:42

0 answers