Requesting for failing API

1

I'm having a problem trying to make a request for a test API ... the connection is only successful if Access-Control-Allow-Origin is set to all * .

The error in the browser: Content Security Policy: As configurações da página bloquearam o carregamento de um recurso em http://localhost:3000/data.json (“default-src”) .

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = 3000

app.use(bodyParser.json())
app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000')
    //res.setHeader('Access-Control-Allow-Origin', '*')
    res.setHeader('Access-Control-Allow-Methods', 'GET')
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type')
    res.setHeader('Access-Control-Allow-Credentials', true)
    next()
})

app.get('/data.json', (req, res) => {
    res.set('Content-Type', 'application/json')
    res.set('Accept-Charset', 'utf-8')
  const data = {'data': 'test'}
    res.send(JSON.stringify(data))
})
app.listen(port, () => {
    console.log('Servidor rodando http://localhost:${port}/data.json')
})

//resquisição no cliente
fetch('http://localhost:3000/data.json')
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(err => console.error('Failed retrieving information', err))

Remembering that the request is made from a local address http://localhost:3000/

UPDATE

Despite being res.setHeader('Content-Security-Policy', 'script-src \'self\' http://localhost:3000') , the Headers in the request remain default Content-Security-Policy default-src 'none' ; script-src resource:;

    
asked by anonymous 22.06.2018 / 18:55

1 answer

0

I think the address is accurate or a pattern.

res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000/*')

for files any request on localhost: 3000 or

res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000/data.json')

Only release data.json.

The other day I broke my head with this too, try the 'cors' package.     

22.06.2018 / 20:55