php发送post请求,koa2接受数据

test.php


function send_post($url, $post_data) {
    $postdata = http_build_query($post_data);
    $options = array(
        'http' => array(
            'method' => 'POST',
            'header' => 'Content-type:application/x-www-form-urlencoded',
            'content' => $postdata,
            'timeout' => 15 * 60 // 超时时间(单位:s)
        )
    );
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    return $result;
}
$post_data = array(
    'order_id' => '1445',
    'order_sn' => '142251244555'
);
//koa接收post接口,需要加上http://
$url = 'http://localhost:3000/orderinfo';

$re = send_post($url,$post_data);
echo ($re);

app.js

const Koa = require('koa');
const bodyParser = require('koa-bodyparser');

// 等于const router = require('koa-router')();
const Router = require('koa-router');
const router = new Router();
const app = new Koa();


// log request URL:
app.use(async (ctx, next) => {
    console.log(`${ctx.request.method} ${ctx.request.url}`); // 打印URL
    await next(); // 调用下一个middleware
});

// add get-url-route:
router.get('/orderinfo/:id', async (ctx, next) => {
    var
        order_id = ctx.params.order_id,
        order_sn = ctx.params.order_sn;
    console.log(`${order_id},${order_sn}`);
    ctx.response.body = `

Hello, ${order_id}${order_sn}!

`
; }); router.get('/', async (ctx, next) => { ctx.response.body = '

this is qioku fabric API!

'
; }); router.get('/order', async (ctx, next) => { ctx.response.body = `

order_id:

order_sn:

`
; }); // add post-url-route: router.post('/orderinfo', async (ctx, next) => { var order_id = ctx.request.body.order_id || '', order_sn = ctx.request.body.order_sn || ''; //console.log(ctx.request); console.log(`${order_id},${order_sn}`); // 返回 ctx.response.body = '

这是第'+`${order_id}`+'份订单,订单号为'+`${order_sn}`+'!

'
; }); /*app.use(async (ctx, next) => { const start = new Date().getTime(); // 当前时间 await next(); // 调用下一个middleware const ms = new Date().getTime() - start; // 耗费时间 console.log(`Time: ${ms}ms`); // 打印耗费时间 });*/ // 对于任何请求,app将调用该异步函数处理请求: // ctx是koa封装了request和response的变量 // next是koa传入的将要处理的下一个异步函数 app.use(async (ctx, next) => { await next(); ctx.response.type = 'text/html'; ctx.response.body += '

Hello, koa2!

'
; }); // 必须在router之前 app.use(bodyParser()); // add router middleware: app.use(router.routes()); // 在端口3000监听: app.listen(3000); console.log('app started at port 3000...');

结果:php发送post请求,koa2接受数据_第1张图片

form.html也可以接受,注意http://

<form action="http://localhost:3000/orderinfo" method="post">
    <p>order_id: <input name="order_id" value=""></p>
    <p>order_sn: <input name="order_sn" value=""></p>
    <p><input type="submit" value="Submit"></p>
</form>

你可能感兴趣的:(javascript,php,javascript,前端,node.js)