express 写POST接口,fetch请求

express后端

express里新建接口js文件apitest.js

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser')
var request = require('request');

router.use(bodyParser.urlencoded({ extended: false, limit: 2 * 1024, parameterLimit: 1000}))

router.post('/', function (req0, res0) {
    //请求刷新时的token,,token='555555555'  56819
    let update = req0.body
    if(update.token != '555555555'){
        res0.send('失败')
        return
    }

    //返回给客户端的json数据
     res0.json({
          name: 'username',
          age:'userage',
      })
    
})

module.exports = router;

再在app.js里引入

var apitest = require('./routes/apitest')
app.use('/apitest', apitest)

客户端(RN)

fetch发起POST请求

function getTest (){
    fetch(`https://www.wefishbone.com/apitest/`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            token: '555555555'
        })
    }).then((response)=>response.json()).then((json)=>{
        console.log('请求成功',json)
    }).catch((err)=>{console.log(err)})
}

你可能感兴趣的:(express 写POST接口,fetch请求)