2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SlackのIncomingWebhookにNuxt.js+axiosでメッセージを送る

Posted at

やりたいこと

何気にやったことがなかったSlackのIncomming Webhookを叩くという処理をやってみる

環境

nuxt.jsとaxiosを使ってやってみます

% sw_vers
ProductName:    Mac OS X
ProductVersion: 10.15.7
BuildVersion:   19H2

% docker version
Client: Docker Engine - Community
 Cloud integration: 1.0.1
 Version:           19.03.13
 API version:       1.40

# npm -v
6.14.8

# npx nuxt -v
@nuxt/cli v2.14.12

Incoming Webhookを有効にする

まずは準備。
slackの指示通りに設定します
すると後に使うwebhookURLが発行されます

実装

npm install

axiosを使って送信します
また、webhookURLは.envに記述するのでdotenvもインストールします


$ npm install @nuxtjs/axios @nuxtjs/dotenv
package.json
{
  "name": "api_practice",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate"
  },
  "dependencies": {
    "@nuxtjs/axios": "^5.12.2",
    "@nuxtjs/dotenv": "^1.4.1",
    "@nuxtjs/pwa": "^3.0.2",
    "bootstrap": "^4.5.2",
    "bootstrap-vue": "^2.17.3",
    "core-js": "^3.6.5",
    "nuxt": "^2.14.6"
  },
  "devDependencies": {}
}

edit index.vue

ボタンを押せば'テストメッセージですの'がslackに投稿されます

index.vue
<template>
  <div class="container">
      <button @click="send">slackに送信</button>
  </div>
</template>

<script>
const axios = require('axios');

export default {
  methods: {
    send: function () {
      let params = new URLSearchParams();
      let message = {text: 'テストメッセージですの'}
      params.append('payload', JSON.stringify(message));
      axios.post(process.env.SLACK_URL, params).then(res => {
        console.log(res);
      }).catch(err => {
        console.log(err);
      });
    }
  }
}
</script>

slackの仕様が最近変わったらしく、メッセージをpayloadというプロパティに入れる必要があるみたいです
またpostで送る際にCORF?エラーが出るため、axiosのドキュメントを参考にURLSearchParamsを使用しました

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?