D
D
Dragondragon2021-07-03 10:25:27
JavaScript
Dragondragon, 2021-07-03 10:25:27

How to implement CORS policy in fetch?

in general, there is a fetch request

fetch('http://localhost:3000', {
    headers: {
        'Content-Type': 'text/plain'
    }
})
    .then(res => {
       // img.style.background = `url(http://localhost:3000) no-repeat`
        console.log(res)
        res.text().then(data2 => {
            console.log(data2)
        })
    })

There is a code on the server
var http = require('http')
var data2 = 'hello'

http.createServer(function(req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  	res.end(data2);
  console.log('img')
}).listen(3000)
console.log('Сервер работает')


Error when sending request
Access to fetch at ' localhost:3000 ' from origin ' localhost ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
what is wrong with my code , with the option to set mode: 'no-cors' already fetch can not pick up a request from both my server and from a third-party

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2021-07-03
@Drakondr

- res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.writeHead(200, {
+     'Content-Type': 'text/plain',
+     'Access-Control-Allow-Origin': '*'
+ });

S
Sergey Sokolov, 2021-07-03
@sergiks

Is this happening in Chrome? There is a bug that does not allow working with localhost.
Try to register in hostsany domain pointing to the address 127.0.0.1and work with it.
And, of course, you need to add a header to the server responsesAccess-Control-Allow-Origin: *

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question