GuzzleHttp模拟表单提交 并用nodejs接受数据
php代码
use GuzzleHttp\Client;
$array = array(
'token'=>$token
);
$data = json_encode($array);
$client = new Client();
$response = $client->request('POST', $url, [
'form_params' => [
'token' => $token,
'other_field' => '123',
'nested_field' => [
'nested' => 'hello'
]
]
]);
// return redirect("http://localhost:3000")->with('token',$token);
return $response;
js接收数据
const bodyParser = require('body-parser');
server.listen(80);
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.post('/', async (req, res) => {
let body =req.body;
let token = req.body.token;
res.sendFile(__dirname + '/views/index.html');
});
PHP 发送 HTTP 请求的方式
那么这里整理一下除了使用 cURL 外 PHP 发送 HTTP 请求的方式。
1.cURL
略过
2.stream 流的方式
stream_context_create 作用:创建并返回一个文本数据流并应用各种选项,可用于 fopen (), file_get_contents () 等过程的超时设置、代理服务器、请求方式、头信息设置的特殊过程。
以一个 POST 请求为例:
<?php
/**
* Created by PhpStorm.
* User: tanteng
* Date: 2017/7/22
* Time: 13:48
*/
function post($url, $data)
{
$postdata = http_build_query(
$data
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
return $result;
}
关于 PHP stream 的介绍文章:https://www.oschina.net/translate/understa…
3.socket 方式
使用套接字建立连接,拼接 HTTP 报文发送数据进行 HTTP 请求。
一个 GET 方式的例子:
<?php
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: www.example.com\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)) {
echo fgets($fp, 128);
}
fclose($fp);
}