【个人笔记重点,不作为参考】主题:restify搭建模拟RESTful API

本文介绍了RESTful架构的原理,以及Node.js中restify框架的使用方法,包括安装、配置插件如Accept Parser、QueryParser和BodyParser,以及如何编写基于REST的API。此外,还提供了处理跨域问题的解决方案,并展示了使用curl工具测试API的例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:

本地测试时,端口不同,涉及跨域。控制台提示, 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

  1. 新建一个app.js文件

    $ touch app.js
    
  2. 引入 restify 模块

    var restify = require('restify');
  3. 创建服务</

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值