node允许跨域以及获取Ajax请求的参数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/well2049/article/details/79473231

设置node后台允许跨域请请求很简单,在入口页面app.js添加代码:

//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    next();
});

再说下使用Ajax的post请求方式发送的数据,在node服务器端如何获取:
在前台页面发送post 必须注意以下几点:

  1. 发给后台服务端的数据格式必须为json字符串
  2. 必须规定contentType:"application/json"
  3. 返回的数据设置为dataType:'json' 这个不是必须的。

案例:

var qdata = {'name':'well','pad':"123"};  
      var fodata = JSON.stringify(qdata);//把数据转换为字符串
      $.ajax({
        url:'http://localhost:3800/news/about',
        dataType:'json',
        type:'GET',
        data: fodata,
        contentType:"application/json",
        success: function(result){
          console.log(typeof result)
          console.log(result)
        },
        error:(error)=>{
          console.log(error)
        }
      })

在服务端必须设置以下几点:

  1. 安装body-parser 模块 npm install body-parser --save
  2. 在app.js 也就是服务端的入口设置json 解析,无论在哪个文档获取参数都必须在入口的页面设置。
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

其次:使用get 方式相对比较简单些。
参数可以是对象,可以是字符串也不用设置类型,案例:
前台页面

function submit(){
      var form = $('form').serialize();
      var qdata = {name:'well', pwd:"123"};  

      $.ajax({
        url:'http://localhost:3800/news/about',
        dataType:'json',
        type:'GET',
        data: form,  // form 和qdata  两种数据都可以

        success: function(result){
          console.log(typeof result)
          console.log(result)
        },
        error:(error)=>{
          console.log(error)
        }
      })
    }

服务端页面:

router.get('/about', function(req, res) {
  console.log(req.query.name);
  res.send({status:200, error: 'message',data:''});
});

猜你喜欢

转载自blog.csdn.net/well2049/article/details/79473231