关于node.js跨域的问题?
使用node的express框架搭建的mockjs环境,设置了跨域,但是好像失效了。
对应的地址是http://localhost:5000/test
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Headers', 'Content-type');
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,PATCH");
res.header('Access-Control-Max-Age',1728000)
next();
});
但是在5500的访问报错
$.get('http://localhost:5000/test', function (data) {
console.log(JSON.parse(data));
})
解决方案
前端也要处理跨域的问题
使用jsonp,
$.ajax({
url: 'http://localhost:5000/test',
type: 'get',
dataType: 'jsonp', // 请求方式为jsonp
// jsonpCallback: "onBack", // 自定义回调函数名
success(res){
console.log(res)
});
对应后台修改为jsonp
app.get('/test', function (req, res) {
res.jsonp(Mock.mock({
"status": 200,
"data|1-9": [{
"name|5-8": /[a-zA-Z]/,
"id|+1": 1,
"value|0-500": 20
}]
}));
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
前端使用nginx反向代理,解决跨域