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)建了兩個應(yīng)用,一個是用戶訪問的app(客戶端),另外一個是api作為請求的接口。
// app middleware app.use(express.static(__dirname + '/public')); // api middleware api.use(logger('dev')); api.use(bodyParser.json());
把app指向public目錄
一些中間件,把app指向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)對目錄的請求,響應(yīng)的時候進行限制,比如來自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');
最后針對指定目錄下的put訪問,console出請求體。
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)建一個http請求,初始化一個put請求,向3001(也就是api應(yīng)用)下的user/1,發(fā)送了一串json,完畢
流程
用戶訪問localhost:3000, express把域名指向了文件系統(tǒng)public目錄下的index.html,index.html通過js向3001端口發(fā)布了一個http的put請求,并上傳了一串json。
api(localhost:3001)接收到這個請求,先檢查響應(yīng)類型,響應(yīng)類型確定源和類型以后繼續(xù)下一步,執(zhí)行到 api.put 里面的 console出請求體。
https://github.com/strongloop/express/tree/master/examples/cors
以上就是Node express 官方示例cors跨域解析的詳細(xì)內(nèi)容,更多關(guān)于Node express cors跨域的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
nodejs+express+multer搭建文件上傳文件預(yù)覽功能
Express 是一個簡潔而靈活的 node.js Web應(yīng)用框架, 提供了一系列強大特性幫助你創(chuàng)建各種 Web 應(yīng)用,和豐富的 HTTP 工具,今天給大家分享nodejs+express+multer搭建文件上傳文件預(yù)覽功能,感興趣的朋友一起看看吧2025-03-03詳解node單線程實現(xiàn)高并發(fā)原理與node異步I/O
本篇文章主要介紹了node單線程實現(xiàn)高并發(fā)原理與node異步I/O ,具有一定的參考價值,有興趣的可以了解一下2017-09-09