如何使用get或post方法连接并执行ajax?

时间:2015-04-02 15:22:35

标签: javascript jquery ajax node.js google-chrome

我有这个JQuery代码,但它没有获得成功总是给予以下:

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');

1 个答案:

答案 0 :(得分: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/