问题:
本地测试时,端口不同,涉及跨域。控制台提示, No 'Access-Control-Allow-Origin' header is present on the requested resource.
解决办法:(重点为: res.header("Access-Control-Allow-Origin", "*"); /*表示允许任意域*/)
方法1. 所有接口
server.use(
function crossOrigin(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
return next();
});
方法2.某一个接口
server.get('/person', function(req, res){
res.send({user: 'root', password: '123qwe..'});
res.header("Access-Control-Allow-Origin", "*");
console.log('Get request from '+req.method);
});
什么是 RESTful 架构?
具象状态传输(英文:Representational State Transfer,简称REST)是Roy Thomas Fielding博士于2000年在他的博士论文 “Architectural Styles and the Design of Network-based Software Architectures” 中提出来的一种万维网软件架构风格。
目前在三种主流的Web服务实现方案中,因为REST模式与复杂的SOAP和XML-RPC相比更加简洁,越来越多的web服务开始采用REST风格设计和实现。例如,Amazon.com提供接近REST风格的Web服务执行图书查询;雅虎提供的Web服务也是REST风格的。
具体可以阅读 阮一峰 的日志 RESTful API 设计指南 ,或是参考 维基百科
什么是 restify 框架?
restify is a node.js module built specifically to enable you to build correct REST web services. It intentionally borrows heavily from express as that is more or less the de facto API for writing web applications on top of node.js.
restify 是专门帮助你建立正确的 REST Web 服务的 Node.js 模块,它有意地大量借鉴了Express。
安装使用 restify
安装
$ npm install restify
编写基于 REST 的 API
-
新建一个
app.js
文件$ touch app.js
-
引入
restify
模块var restify = require('restify');
-
创建服务</