在一個(gè)項(xiàng)目上想用NodeJS,所以邊學(xué)邊練。第一個(gè)遇到的問(wèn)題就是跨域訪問(wèn)控制問(wèn)題。很多初學(xué)者會(huì)遇到同樣問(wèn)題。 問(wèn)題在前端的JS(http://localhost/xxx)中ajax訪問(wèn)后端RestAPI(http://localhost:3000/….)時(shí)(Chrome)報(bào)錯(cuò):
方案解決代碼如下: var express = require('express'); var app = express(); //設(shè)置跨域訪問(wèn) 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...'); |
|
來(lái)自: 昵稱(chēng)597197 > 《HTML5》