node-express(1)建立post、get、跨域问题解决方案

首先下载express:npm i express

let ess=require('express');
let app=ess();
let bodyParser=require('body-parser');//当客户端的请求为post请求时需要通过它去解析客户端传过来的数据
app.all('*',function(req,res,next){
  res.header('Access-Control-Allow-Origin', '*');//的允许所有域名的端口请求(跨域解决)
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Methods', '*');
  res.header('Content-Type', 'application/json;charset=utf-8');
  next();
})
app.listen(8083,function(){//监听8083端口
  console.log("服务开启成功");
});

app.use(bodyParser.urlencoded({}));//中间层对post请求的req进行解析
//注意当app.listen监听到指定端口出现请求时,会执行最先匹配的方法,如果匹配了多个方法,且上一个执行的方法中执行了next方法 那么匹配的所有方法就会一个一个执行下去
//知道上一个方法中没有执行next;
//app.use()的第一个参数可以是正则表达式,不设参数则匹配所有路径
app.use('/get',function(req,res){
   res.json({name:'你发出的是get请求'})
})
//除了使用use意外还可以使用app.get()/app.post()参数都是一样
app.use('/post',function(req,res,next){
  console.log(req.body);
  res.json({a:"你发出的是post请求传过来的值为"+req.body.name+'1'});
})
// app.use('/post*',function(req,res){
//   console.log('第二次执行');
//   res.json({a:"你传过来的值为"+req.body.name+'1'});
// })

猜你喜欢

转载自www.cnblogs.com/wrhbk/p/11084321.html
今日推荐