使用fetch调用node.js的Resuful服务

在目前的软件架构中,慢慢又有这样的趋势,就是在前端和业务接口层中间再加入一层,如下图:

在这样的结构中,JS前端和web层都是前端开发工程师来完成,可以大大提升开发效率。JS前端和web层还是可以通过Restful接口来进行通讯。即JS前端通 fetch 调用 web层由node.js提供的服务。下面是一个具体的例子,在实际调试时卡了半天,所以特此一记。

前端:

    const url = "http://127.0.0.1:3001/createAccount";

       
        fetch(url, {
            method: "POST",
            mode: "cors",
            body:"pwd=sdd",
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }

        }).then(response => response.json())
            .then(result => {
                // 在此处写获取数据之后的处理逻辑
                console.log(result);
            }).catch(function (e) {
            //console.log("fetch fail", JSON.stringify(params));
            alert(e);
        });    

上面标红的两处非常重要,在百度有些文章的写法如下:

             let formData = new FormData();

            formData.append("pwd","hello");  

     fetch(url, {
method: "POST",
mode: "cors",
body:formData,
.....
.......
但是发现在web端无法获法提交的参数


web端
 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");
    console.log(req.body.pwd) ;   //获到提交的参数
    res.send({
       /* success: true,
        code:0,*/
        "msg":"success"
    });
 

由于web端使用了express框架,下面是express的相关配置:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var webRouter = require('./web_router');

var app = express();



app.use(logger('dev'));
//const bodyParser = require('body-parser');
//app.use(bodyParser.json());//数据JSON类型
//app.use(bodyParser.urlencoded({ extended: false }));//解析post请求数据
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use('/', webRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;





猜你喜欢

转载自www.cnblogs.com/hzhuxin/p/10031940.html
今日推荐