Node express 官方示例cors跨域解析
node express
最近學(xué)習(xí)node以及express,看例子看的頭疼,剛看完cors,寫一下記錄下來。
index.js
var express = require('../..');
var logger = require('morgan');
var app = express();
var bodyParser = require('body-parser');
var api = express();首先創(chuàng)建了兩個(gè)應(yīng)用,一個(gè)是用戶訪問的app(客戶端),另外一個(gè)是api作為請(qǐng)求的接口。
// app middleware
app.use(express.static(__dirname + '/public'));
// api middleware
api.use(logger('dev'));
api.use(bodyParser.json());把a(bǔ)pp指向public目錄
一些中間件,把a(bǔ)pp指向public目錄,使用log,body解析為json。
/**
* CORS support.
*/
api.all('*', function(req, res, next){
if (!req.get('Origin')) return next();
// use "*" here to accept any origin
res.set('Access-Control-Allow-Origin', 'http://localhost:3000');
res.set('Access-Control-Allow-Methods', 'PUT');
res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
// res.set('Access-Control-Allow-Max-Age', 3600);
if ('OPTIONS' == req.method) return res.send(200);
next();
});這里我的理解是 api應(yīng)對(duì)目錄的請(qǐng)求,響應(yīng)的時(shí)候進(jìn)行限制,比如來自3000端口,PUT方式,然后執(zhí)行next
/**
* PUT an existing user.
*/
api.put('/user/:id', function(req, res){
console.log('req.body'+req.body);
console.log(req.body);
res.send(204);
});
app.listen(3000);
api.listen(3001);
console.log('app listening on 3000');
console.log('api listening on 3001');最后針對(duì)指定目錄下的put訪問,console出請(qǐng)求體。
public目錄下的index.html
var req = new XMLHttpRequest;
req.open('PUT', 'http://localhost:3001/user/1', false);
req.setRequestHeader('Content-Type', 'application/json');
req.send('{"name":"tobi","species":"ferret"}');
console.log(req.responseText);創(chuàng)建一個(gè)http請(qǐng)求,初始化一個(gè)put請(qǐng)求,向3001(也就是api應(yīng)用)下的user/1,發(fā)送了一串json,完畢
流程
用戶訪問localhost:3000, express把域名指向了文件系統(tǒng)public目錄下的index.html,index.html通過js向3001端口發(fā)布了一個(gè)http的put請(qǐng)求,并上傳了一串json。
api(localhost:3001)接收到這個(gè)請(qǐng)求,先檢查響應(yīng)類型,響應(yīng)類型確定源和類型以后繼續(xù)下一步,執(zhí)行到 api.put 里面的 console出請(qǐng)求體。
https://github.com/strongloop/express/tree/master/examples/cors
以上就是Node express 官方示例cors跨域解析的詳細(xì)內(nèi)容,更多關(guān)于Node express cors跨域的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
如何從頭實(shí)現(xiàn)一個(gè)node.js的koa框架
這篇文章主要介紹了如何從頭實(shí)現(xiàn)一個(gè)node.js的koa框架,koa.js是最流行的node.js后端框架之一,有很多網(wǎng)站都使用koa進(jìn)行開發(fā),同時(shí)社區(qū)也涌現(xiàn)出了一大批基于koa封裝的企業(yè)級(jí)框架。,需要的朋友可以參考下2019-06-06
nodejs+express+multer搭建文件上傳文件預(yù)覽功能
Express 是一個(gè)簡(jiǎn)潔而靈活的 node.js Web應(yīng)用框架, 提供了一系列強(qiáng)大特性幫助你創(chuàng)建各種 Web 應(yīng)用,和豐富的 HTTP 工具,今天給大家分享nodejs+express+multer搭建文件上傳文件預(yù)覽功能,感興趣的朋友一起看看吧2025-03-03
Node.js實(shí)現(xiàn)格式化時(shí)間的兩種方法詳解
在 Node.js 開發(fā)中,格式化時(shí)間是一個(gè)常見的需求,本文將介紹兩種格式化時(shí)間的方式,即使用 JavaScript 內(nèi)置方法 和 使用 npm 包 moment,需要的可以了解下2025-03-03
詳解node單線程實(shí)現(xiàn)高并發(fā)原理與node異步I/O
本篇文章主要介紹了node單線程實(shí)現(xiàn)高并發(fā)原理與node異步I/O ,具有一定的參考價(jià)值,有興趣的可以了解一下2017-09-09

