0
0

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 1 year has passed since last update.

Cloud functions で POST した際に、req.body のデータ が undefined になる場合

Last updated at Posted at 2022-05-17

備忘録。

Cloud Functions に POST したい場合

Cloud Function 側

exports.test = (req, res) => {

  const cors_domain = ["http://your-domain.com", "http://your-domain2.com"]
  const origin = req.headers.origin
  if (cors_domain.indexOf(origin) >= 0) {
    res.set('Access-Control-Allow-Origin', origin)
  }
  res.set('Access-Control-Allow-Credentials', true)

  const test_params = req.body.params1

  res.status(200).send({params: test_params})

これに、フロントから fetch すると、

const your_data = {params1: "hoge"}

fetch("your-cloud-functions-path.com/",
  { method: "POST",
    body: JSON.stringify(your_data)}
)
.then((response) => {
  return response.json()
})
.then((result) => {
  console.log(result)
})
{params: undefined}

と undefined が、返ってくる。

結論

fetch 側 の header に 'Content-Type': 'application/json; charset=utf-8' を追加し、cloud functions 側 の res に headers の Content-Type を許可するようにする。

Cloud Functions

// cors などを設定している部分に、下のプログラムを入れる。
res.set('Access-Control-Allow-Headers', 'Content-Type')

fetch 側

// headers を追加する
const headers = {
  'Accept': 'application/json',
  'Content-Type': 'application/json; charset=utf-8'
}

const your_data = {params1: "hoge"}
fetch("your-cloud-functions-path.com/",
  { method: "POST",
    headers,
    body: your_data}
)

これで、POST で データ渡し ができるようになります。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?