Pass access control in connection (node.js)

I am launching static pages via connect

var connect = require('connect'); connect.createServer( connect.static(__dirname)).listen(8080); 

I need to add a response header to the code above to get around access control

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

How to add it to the connection code above.

+4
source share
1 answer

I answered this question here

Corresponding code

 var http = require("http"); var connect = require('connect'); var app = connect() .use(connect.logger('dev')) .use(connect.static('home')) .use(function(req, res){ res.setHeader("Access-Control-Allow-Origin", "http://example.com"); res.end('hello world\n'); }); var server = http.createServer(app); server.listen(9999, function () { console.log('server is listening'); }); 

Enable cors provides an excellent resource for adding cors to your server.

If you need to send cors headers with every static file you serve and you need to use connect, do this

go to connect\node_modules\send\lib\send.js

find the setHeader function in the file. This is the function that actually sets the title for your static resources. Just add

res.setHeader("Access-Control-Allow-Origin", "your domain");

and all your files will have a cors header

If you just use connect to serve static files and don't require any other functions, use send instead. Thus, you will have access to all these methods directly and will not need to edit files. You can simply add headers from your server creation method. Here is a sample code

 var http = require("http"); var connect = require('connect'); var send = require('send'); var url = require('url'); var app = http.createServer(function(req, res){ // your custom error-handling logic: function error(err) { res.statusCode = err.status || 500; res.end(err.message); } // your custom directory handling logic: function redirect() { res.statusCode = 301; res.setHeader('Location', req.url + '/'); res.end('Redirecting to ' + req.url + '/'); } function setRoot(){ res.setHeader("Access-Control-Allow-Origin", "http://example.com"); return './public'; } function setIndex(){ res.setHeader("Access-Control-Allow-Origin", "http://example.com"); return '/index.html'; } send(req, url.parse(req.url).pathname) .root(setRoot()).index(setIndex()) .on('error', error) .on('directory', redirect) .pipe(res); }).listen(3000); 
+2
source

Source: https://habr.com/ru/post/1489294/


All Articles