新人求助ajax请求express失败
发布于 8 年前 作者 204beyond 14782 次浏览 来自 问答

头几天开始关注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)); } }); 多谢

11 回复

补充一句,直接浏览器http://localhost:3000/这样请求是没问题的,正常返回

看浏览器控制台输出什么错误

@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.

跨域了,详细自己搜索 自豪地采用 CNodeJS ionic

AjaxURL改下 127.0.0.1:3000 From Noder

浏览器安全限制,一般情况下禁止跨域发起异步请求 你客户端的URL请求地址用相对路径,不要用绝对路径就可以了

/跨域中间件/

    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;

如此可以解决问题

@zouzhenxing 这是教坏小朋友嘛,随便*跨域不太好吧- -练练手就无所谓了

感谢各位的帮助,跨域的问题已经解决,本来还有个json解析的问题想问,但是后来自己百度了下,也解决了, 我想问下,npm中的模块文档是不是没有中文的啊,我的英文水平比较low,读起来好吃力啊, 有没有中文的资源推荐下?

@DevinXian 你的意思是*应该用指定的域替换?还是用其他的方式解决跨域问题呢?

@204beyond 我自己一般是通过nginx代理过滤设置,不过*也不会出啥大乱子~

回到顶部