Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

jquery - POST AJAX request denied - CORS?

I have setup CORS on my node.js server on port 5000 as follows:

var app = express();

app.use(cors()); //normal CORS
app.options('*', cors()); //preflight 

app.post('/connect', function(req, res) { 
    console.log("Connection request received !")
});

var port = 5000;
app.listen(port, function () {
    console.log('Listening on port '+port);
});

I am now trying to send AJAX POST requests using JQuery like so, in a static web page open from my hard disk :

var xhr = $.post({
            url: 'http://localhost:5000/connect',
            complete: function() {
                console.log("done !")
            },
            crossDomain: true
        });

xhr.fail(function(xhr, status, error){
    alert(error)
})

The complete function is never called, and the only alert I get is an alert from the XHR fail handler, containing the following error :

NS_ERROR_DOM_BAD_URI: Access to restricted URI denied

I think CORS is well-configured, what am I missing ?


EDIT : for those in my case, the best solution I could find was to send the page from the server :

app.use(express.static('web'))

app.get("/", function(req, res) {
    res.sendFile(__dirname + '/web/HTML/index.html');
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is the code I am using. It is located in my app.js file

app.all("/*", function (req, res, next) {

  res.header("Access-Control-Allow-Origin", req.headers.origin);
  res.header("Access-Control-Allow-Credentials",true);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type,Accept,X-Access-Token,X-Key,Authorization,X-Requested-With,Origin,Access-Control-Allow-Origin,Access-Control-Allow-Credentials');
  if (req.method === 'OPTIONS') {
    res.status(200).end();
  } else {
    next();
  }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...