2015-04-02 38 views
-2

我有這樣的jQuery代碼,但它沒有得到成功總是給人以下幾點:如何連接並使用get或post方法執行ajax?

XMLHttpRequest cannot load http://localhost:8080/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8383' is therefore not allowed access. (17:21:10:896 | error, javascript) 
    at win_1.html 
Error: undefined (17:21:10:902) 
    at win_1.html:18 
Debugging session with browser was closed. 

的index.html:

<script src=http://code.jquery.com/jquery-1.11.2.min.js ></script> 
<body> 
response here: <p id="lblResponse">fill me in</p> 
<script type="text/javascript"> 
$(document).ready(function() { 
    $.ajax({ 
    url: 'http://localhost:8080', 
    // dataType: "jsonp", 
    data: '{"data": "TEST"}', 
    type: 'POST', 
    //jsonpCallback: 'callback', // this is not relevant to the POST anymore 
    success: function (data) { 
     var ret = jQuery.parseJSON(data); 
     $('#lblResponse').html(ret.msg); 
     console.log('Success: ') 
    }, 
    error: function (xhr, status, error) { 
     console.log('Error: ' + error.message); 
     $('#lblResponse').html('Error connecting to the server.'); 
    }, 
    }); 
}); 
</script> 
</body> 

的NodeJS-server.js:

var http = require('http'); 
var util = require('util') 
http.createServer(function (req, res) { 
    console.log('Request received: '); 
    util.log(util.inspect(req)) 
    // this line helps you inspect the request so you can see whether the data is in the url (GET) or the req body (POST) 
    util.log('Request recieved: \nmethod: ' + req.method + '\nurl: ' + req.url) 
    // this line logs just the method and url 

    res.writeHead(200, { 'Content-Type': 'text/plain' }); 
    req.on('data', function (chunk) { 
     console.log('GOT DATA!'); 
    }); 
    res.end('callback(\'{\"msg\": \"OK\"}\')'); 

}).listen(8080); 
console.log('Server running on port 8080'); 
+0

可能重複(http://stackoverflow.com/questions/18310394/no-access-control -allow-origin-node-apache-port-issue) – dave 2015-04-02 15:26:19

+0

否 - 那沒有解決問題 – YumYumYum 2015-04-02 15:28:54

+0

你在哪裏運行這段代碼?在本地主機上? – 2015-04-02 15:33:55

回答

1

添加此之後您的console.log()

console.log('Request received: '); if (req.method === 'OPTIONS') { //add needed headers var headers = {}; headers["Access-Control-Allow-Origin"] = "*"; headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS"; headers["Access-Control-Allow-Credentials"] = true; headers["Access-Control-Max-Age"] = '86400'; // 24 hours headers["Access-Control-Allow-Headers"] = "X-Requested-With, Access-Control-Allow-Origin, X-HTTP-Method-Override, Content-Type, Authorization, Accept"; // respond to the request res.writeHead(200, headers); res.end(); } else { //rest of your code }

來源: https://annasob.wordpress.com/2012/01/11/getting-around-cors-with-node-js/

[否 '訪問控制允許來源' - 節點/ Apache的端口號]的
+1

非常好。這就是應該如何回答問題。而不是減投票。欣賞它,確切的點。 – YumYumYum 2015-04-16 09:04:53

相關問題