使用Google Apps脚本发布数据

时间:2017-12-01 03:49:08

标签: php google-apps-script gmail add-on

我正在尝试将谷歌脚本中的JSON数据发布到URL但是出现上述错误。

  

“错误请求:http://api.dev/api.php/project_task/

https://imgur.com/a/b3EYo

这是我的代码:

function testApi() { 
var data = {
   "user_id": 12,
   "username": "Son Ha",
   "creator_id": 35,
   "creator_username": "Simon Ha",
   "status": 1
  };
 var options = {
   "method" : "post",
   "contentType" : "application/json",
   "payload" : JSON.stringify(data)
  };
 UrlFetchApp.fetch('http://api.dev/api.php/project_task/', options);
}

我的PHP Api代码:http://api.dev/api.php/project_task/

$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);
$link = mysqli_connect('localhost', 'root', '', 'base_test');
mysqli_set_charset($link,'utf8');
$table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
$key = array_shift($request)+0;
switch ($method) {
    case 'GET':
        $sql = "select * from `$table`".($key?" WHERE id=$key":''); break;
    case 'PUT':
        $sql = "update `$table` set $set where id=$key"; break;
    case 'POST':
        $sql = "INSERT INTO projecttasks 
(user_id, username, creator_id, creator_username, status)
    VALUES (1, 'Tom B. Erichsen', 1, 'Stavanger', '4006')"; break;
    case 'DELETE':
        $sql = "delete `$table` where id=$key"; break;
}

$result = mysqli_query($link,$sql);
if (!$result) {
    http_response_code(404);
    die(mysqli_error());
}
if ($method == 'GET') {
    if (!$key) echo '[';
    for ($i=0;$i<mysqli_num_rows($result);$i++) {
        echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
    }
    if (!$key) echo ']';
} elseif ($method == 'POST') {
    echo mysqli_insert_id($link);
} else {
    echo mysqli_affected_rows($link);
}
mysqli_close($link);

任何人都知道我哪里出错了?感谢。

0 个答案:

没有答案