且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

节点JS-CORS-请求标头字段在飞行前响应中,Access-Control-Allow-Headers不允许授权

更新时间:2022-11-12 09:49:34

下面的代码应该可以工作:

The code below should work:

var express = require("express");
var cors = require("cors");
var app = express();

var corsOptions = {
    origin: ' your_url',
    optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
  }

app.use(function(req, res, next) {
    // res.header("Access-Control-Allow-Origin", "*");
    // res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    // app.header('Access-Control-Allow-Origin', 'http://localhost');
    // app.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    // app.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    // app.header('Access-Control-Allow-Credentials', true);
    next();
});
///products/:id
  app.get('/helloworld', cors(corsOptions), function (req, res, next) {
    res.json({msg: 'This is CORS-enabled for only example.com.'});
  })

  app.listen(3000, function() {
      console.log("CORS-enabled web server listening on port 3000");
  });

var response_text;

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
//Get the html of the website
function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        // Check if the XMLHttpRequest object has a "withCredentials" property.
        // "withCredentials" only exists on XMLHTTPRequest2 objects.
        xhr.withCredentials = true;
        xhr.open(method, url, true);
        xhr.send();    
    } else if (typeof XDomainRequest != "undefined") {

      // Otherwise, check if XDomainRequest.
      // XDomainRequest only exists in IE, and is IE's way of making CORS requests.
      xhr = new XDomainRequest();
      xhr.open(method, url);
      xhr.send();
    } else {

      // Otherwise, CORS is not supported by the browser.
      xhr = null;

    }
    return xhr;
  }

  var url = "your_url";

  var xhr = createCORSRequest('GET', url);
  if (!xhr) {
    throw new Error('CORS not supported');
  }

  xhr.onload = function() {
    response_text = xhr.responseText;
    console.log(response_text);
    console.log(values);
    // process the response.
   }

   xhr.onerror = function() {
     console.log('There was an error!');
   }

然后cd到终端中的文件目录并写:
$ node filename.js

Then cd to the file directory in the terminal and write: $ node filename.js

然后它将在 http:上监听// localhost:3000 / helloworld
希望它能起作用。

It will then be listening on http://localhost:3000/helloworld Hope this works.