Cross-Origin Request works on Postman, but not on frontend

Asked

Viewed 552 times

0

I need to access my API for sending emails, but every time I try to do it through my application’s frontend I get a CORS error saying Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://mvtechsolutions.com:21007/contact. (Reason: CORS request did not succeed)

But when I use Postman the email arrives without problems...

I’m using some headers that supposedly would make my frontend application be accepted, but nothing solves...

This is my request for frontend:

const baseUrl = 'https://mywebsiteaddr.com:port/contact'

export default class ContactUs extends Component {

    send = () => {

        const message = this.state.message
        const url = baseUrl
        console.log(message)
        axios.post(url, message)
            .then(this.reset())
            .then(alert('Mensagem enviada'))
    }
}

my index.js (API)

const express = require('express')
const app = express()
const consign = require('consign')
const AllowCors = require('./config/cors')
const bodyParser = require('body-parser')
const cors = require('cors')

const port = 21007
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
app.use(AllowCors)
app.use(cors())

consign()
//.then('./config/middlewares.js')
.then('./api')
.then('./config/routes.js')
.into(app)

app.listen(port, () => {
    console.log(port)
})

My headers:

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

In theory this would be enough to receive the emails, but until then I was not successful... If you can help I would be very grateful!

  • you’re using twice a middleware of Cors, what may be happening is that one may be superimposing the other, tries to take the app.use(AllowCors)

  • 1

    I’ve removed the Allowcors, and I’ve specified my domain. The error has changed, now I have a problem with "mixed active content", but I believe that if I were to deal with this topic I would avoid the main subject. Then I will probably open a new topic. Thank you for replying!

No answers

Browser other questions tagged

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