头几天开始关注node,想用express和ajax弄个网页做练习,但是请求时一直readystate:0…statusText:error,请各位前辈指点下 后台代码 var express = require(‘express’); var app = express(); app.get(’/’, function(req, res){ console.log(req); //res.send(‘hello world’); res.send({name:1234}); }); app.listen(3000); console.log(“server has started”);
前台代码 $.ajax({ type:“get”, contentType: “application/json”, dataType: “json”, url:“http://localhost:3000/”, async:true, data:{id:12345}, success:function(data) { alert(data); // alert($.parseJSON(data)); // $("#indexhtml").test(JSON.stringify(data)); }, error:function(err) { alert(JSON.stringify(err)); } }); 多谢
@captainblue2013 XMLHttpRequest cannot load http://localhost:3000/?id=12345. Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘null’ is therefore not allowed access.
/跨域中间件/
app.all(*,function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
next();
});
//在客户端对ajax进行设定
$.ajaxSettings.crossDomain = true;
如此可以解决问题