0
Hello! I need to pass a string to Node and am receiving the following response in 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 Node and it’s on the same machine that I’m testing. So it’s all local. Below are the CORS policies of my server:
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()
}
Factory at the angle:
(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 I receive 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 strange thing is that for example, everything in that route of "alerts" works, but in this post there not. I’m doing wrong?
in this machine ::3003 intala and enable Cors. https://www.npmjs.com/package/cors
– Israel Zebulon
That’s it. I updated the question, I put the code there.
– Fred