simple ajax request to localhost nodejs server

前端 未结 2 518
后悔当初
后悔当初 2021-01-07 07:18

I wrote very simple server :

/* Creating server */
var server = http.createServer(function (request, response) {
  response.writeHead(200, {\"Content-Type\":         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-07 07:59

    The first error is caused by CORS (Cross Origin Resource Sharing) policy. It's rule by all browsers that you cannot make a request to a remote server in AJAX other than to the current server the script/page was loaded from unless that remote server allows it via Access-Control-Allow-Origin header.

    I suggest serving the page from the same Node.js server. Then it will work. Example, when the request comes to root / page, then serve the index.html file, otherwise, server whatever other content you want.

    var http = require('http'),
        fs = require('fs');
    
    /* Creating server */
    var server = http.createServer(function (request, response) {
        if (request.url == '/' || request.url == '/index.html') {
            var fileStream = fs.createReadStream('./index.html');
    
            fileStream.pipe(response);
        } else {
            response.writeHead(200, {"Content-Type": "text/plain"});
            response.end("Hello World\n");
        }
    });
    
    /*Start listening*/
    server.listen(8000);
    

提交回复
热议问题