LoginSignup
1
1

More than 3 years have passed since last update.

jQueryのajaxでJSONを送るとIntegerがStringになるやつをいろいろ調べた

Last updated at Posted at 2019-11-18

業務中に質問を受けたので検証しました

結論

JSONをJSON.stringify()で囲み、Content-Typeを'application/json'にすることで、Integerのまま送信できました。

参考: jQuery.ajax()

検証ログ

フロント(通信部分のみ)

jQuery
$.ajax({
  url: "http://localhost:3000/api/v1/test",
  type: "POST",
  dataType: "json",
  data: jsonData
}).done(function(r) {
  console.log(r)
})
axios
axios
  .post("http://localhost:3000/api/v1/test", jsonData)
  .then(r => {
    console.log(r)
  })

バックエンド(Express)

const express = require("express")
const cors = require("cors")
const bodyParser = require('body-parser')
const app = express()

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use(cors())
app.use(function (req, res, next) {
  res.setHeader('Content-Type', 'text/plain')
  next()
})

app.listen(3000, function() {})

app.post("/api/v1/test", function(req, res, next) {
  console.log(req.body)
  res.json(req.body)
})

送信データ

パターン1

パターン1
{
  a: [],
  b: [1, 2, 3],
  nulls: {
    a: [, 2, 3],
    b: [, , ,],
    c: [, 2, , ],
    d: [, 2, , 4]
  },
  karas: {
    a: ["", 2, 3],
    b: ["", "", ""],
    c: ["", 2, "",""],
    d: ["", 2, "", 4]
  }
}

パターン2

パターン2
JSON.stringify({
  a: [],
  b: [1, 2, 3],
  nulls: {
    a: [, 2, 3],
    b: [, , ,],
    c: [, 2, , ],
    d: [, 2, , 4]
  },
  karas: {
    a: ["", 2, 3],
    b: ["", "", ""],
    c: ["", 2, "",""],
    d: ["", 2, "", 4]
  }
})

結果

パターン1

jQuery
[Object: null prototype] {
  'b[]': [ '1', '2', '3' ],
  'nulls[a][]': [ '', '2', '3' ],
  'nulls[c][]': [ '', '2' ],
  'nulls[d][]': [ '', '2', '', '4' ],
  'karas[a][]': [ '', '2', '3' ],
  'karas[b][]': [ '', '', '' ],
  'karas[c][]': [ '', '2', '' ],
  'karas[d][]': [ '', '2', '', '4' ] }
axios
{ a: [],
  b: [ 1, 2, 3 ],
  nulls:
   { a: [ null, 2, 3 ],
     b: [ null, null, null ],
     c: [ null, 2, null ],
     d: [ null, 2, null, 4 ] },
  karas:
   { a: [ '', 2, 3 ],
     b: [ '', '', '' ],
     c: [ '', 2, '' ],
     d: [ '', 2, '', 4 ] } }

パターン2

contentType: 'application/json' をセット

jQuery
{ a: [],
  b: [ 1, 2, 3 ],
  nulls:
   { a: [ null, 2, 3 ],
     b: [ null, null, null ],
     c: [ null, 2, null ],
     d: [ null, 2, null, 4 ] },
  karas:
   { a: [ '', 2, 3 ],
     b: [ '', '', '' ],
     c: [ '', 2, '' ],
     d: [ '', 2, '', 4 ] } }
1
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
1
1