simple ajax request to localhost nodejs server

前端 未结 2 436
后悔当初
后悔当初 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条回答
  • 2021-01-07 07:58

    To overcome the CORS, in your node.js file write the below, based on what you need:

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', '*');
    
    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    
    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    
    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题