Answer the question
In order to leave comments, you need to log in
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)
})
})
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('Сервер работает')
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
- res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.writeHead(200, {
+ 'Content-Type': 'text/plain',
+ 'Access-Control-Allow-Origin': '*'
+ });
Is this happening in Chrome? There is a bug that does not allow working with localhost.
Try to register in hosts
any domain pointing to the address 127.0.0.1
and 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 questionAsk a Question
731 491 924 answers to any question