在一個項目上想用NodeJS,所以邊學(xué)邊練。第一個遇到的問題就是跨域訪問控制問題。很多初學(xué)者會遇到同樣問題。 問題在前端的JS(http://localhost/xxx)中ajax訪問后端RestAPI(http://localhost:3000/….)時(Chrome)報錯:
方案解決代碼如下: var express = require('express'); var app = express(); //設(shè)置跨域訪問 app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.header("X-Powered-By",' 3.2.1') res.header("Content-Type", "application/json;charset=utf-8"); next(); }); app.get('/auth/:id/:password', function(req, res) { res.send({id:req.params.id, name: req.params.password}); }); app.listen(3000); console.log('Listening on port 3000...'); |
|