1.接口支持 POST 且前端不用修改
在 action 里设置:
public $enableCsrfValidation = false;
2.添加返回 header:
Yii::$app->response->headers->add('Access-Control-Allow-Origin','*');
3.使用 curl 发出请求,要用的时候经常要从网上查,这里记一下
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 把头信息记录到 output,改为0则不会有头信息 curl_setopt($ch, CURLOPT_HEADER, 1); $output = curl_exec($ch);
4.使服务器可以解析 post 的 json 参数
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'xxx',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
'text/json' => 'yii\web\JsonParser',
],
],
这样当 post 的 Content-Type 是 application/json 或者 text/json 的时候,可以通过
Yii::
$app
->
request
->post() 直接获取到解析后的 Array
5.配置服务器发送邮件
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => false,
'transport' => [
'class'=>'Swift_SmtpTransport',
'host' =>'smtp.exmail.qq.com',
'username'=>'xxx',
'password' =>'xxx',
'port' => 25,
'encryption' => 'tls'
],
'messageConfig'=>[
'charset'=>'UTF-8',
'from' => ['xxx'=>'xxx']
],
],
然后发送邮件的代码如下:
$mail = Yii::$app->mailer->compose();
$mail->setTo($to);
$mail->setSubject($subject);
$mail->setHtmlBody($msg);
if ($mail->send()) {
//success
} else {
// fail
}
6.bindActionParams 函数可以用于在调用 action 之前处理参数或者做某些前置检查,$params 是参数数组,可以直接用 $params['paramName'] 来获取参数值
public function bindActionParams($action, $params)
{
// 这个链接要对外开放,直接放出去
// if ($action->controller->id == 'file' && $action->id == 'listpic') {
// return parent::bindActionParams($action, $params);
// }
if ($action->controller->id == 'test') {
return parent::bindActionParams($action, $params);
}
}