N
N
Nikita2020-12-27 12:04:45
Express.js
Nikita, 2020-12-27 12:04:45

Request from foreign origin blocked: Single origin policy prohibits reading remote resource?

A GET request is made from the client (via axios) to the URL https://mysite.me:5000/api/v1/form?arg=1

The server generates a response

const express = require('express')
const mongoose = require('mongoose')

const app = express()

const PORT = 5000

app.get('/api/v1/form', (req, res) => {
    res.header('Access-Control-Allow-Origin', '*')
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
    res.end()
})

app.listen(PORT, err => {
    err ? console.log(err) : console.log(`[Server] started on port ${PORT}`)
})


But the browser blocks the request due to the missing header. Access-Control-Allow-Origin

What could be the reason for this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita, 2020-12-27
@Prynik

As Lynn "Coffeeman" said , the point was that I did not configure the https server of the node. Transformed the code to the following form and the problem was solved.

const fs = require('fs')
const https = require('https')

const privateKey  = fs.readFileSync('./ssl/server.key', 'utf8');
const certificate = fs.readFileSync('./ssl/server.crt', 'utf8');

const credentials = {key: privateKey, cert: certificate}
const app = express()

const PORT = 5000

app.get('/api/v1/assistant-form', (req, res) => {
    res.header('Access-Control-Allow-Origin', '*')
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
    res.end()
})

const httpsServer = https.createServer(credentials, app)

httpsServer.listen(PORT)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question