zoukankan      html  css  js  c++  java
  • 解决NodeJS+Express模块的跨域访问控制问题:Access-Control-Allow-Origin

    在一个项目上想用NodeJS,在前端的js(http://localhost/xxx)中ajax访问后端RestAPI(http://localhost:3000/….)时(Chrome)报错:

    XMLHttpRequest cannot load http://localhost:3000/auth/xxx/xxx. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

    解决代码:

    方案一:
     
    1. var express = require('express');  
    2. var app = express();  
    3. //设置跨域访问  
    4. app.all('*', function(req, res, next) {  
    5.     res.header("Access-Control-Allow-Origin", "*");  
    6.     res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");  
    7.     res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");  
    8.     res.header("X-Powered-By",' 3.2.1')  
    9.     res.header("Content-Type", "application/json;charset=utf-8");  
    10.     next();  
    11. });  
    12.   
    13. app.get('/auth/:id/:password', function(req, res) {  
    14.     res.send({id:req.params.id, name: req.params.password});  
    15. });  
    16.   
    17. app.listen(3000);  
    18. console.log('Listening on port 3000...');  

    方案二: 

     
      1. var express = require('express');  
      2. var app = express();  
      3.   
      4. app.get('/auth/:id/:password', function(req, res) {  
      5.     res.header("Access-Control-Allow-Origin", "*");   //设置跨域访问  
      6.     res.send({id:req.params.id, name: req.params.password});  
      7. });  
      8.   
      9. app.listen(3000);  
      10. console.log('Listening on port 3000...');  
  • 相关阅读:
    2020软件工程个人作业06————软件工程实践总结作业
    2020软件工程作业01
    班级博客V2.1版本更新日志
    博客园班级手机版
    班级帮助文档
    问题累计
    2020 软件工程作业06
    2020 软件工程作业04
    2020 软件工程作业03
    2020软件工程02
  • 原文地址:https://www.cnblogs.com/winyh/p/7052864.html
Copyright © 2011-2022 走看看