[Error]Uncaught (in promise) TypeError: getList.forEach is not a function

문제상황

Uncaught (in promise) TypeError: getList.forEach is not a function

at VueComponent._callee$ (webpack-internal:///./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/components/BoardList.vue:56) at tryCatch (webpack-internal:///./node_modules/regenerator-runtime/runtime.js:62) at Generator.invoke as _invoke at Generator.prototype. [as next](webpack-internal:///./node_modules/regenerator-runtime/runtime.js:114) at step (webpack-internal:///./node_modules/babel-runtime/helpers/asyncToGenerator.js:17) at eval (webpack-internal:///./node_modules/babel-runtime/helpers/asyncToGenerator.js:28)

문제확인

forEach()메서드는 배열을 순회하지만 객체를 순회하지 못한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script>
  const axios = require('axios').default
  let getList
  export default {
    data () {
      return {
        loading: false,
        list: null,
        error: null
      }
    },
    created () {
      this.getBoardList()
    },
    methods: {
      async getBoardList () {
        getList = await axios.get('/api/board/list')
        getList.forEach(r => this.list.push({ writer: r.writer, title: r.title, content: r.content, regDate: r.regDate }))
      }
    }
  }
</script>

문제해결

(1) http://localhost:8080/api/board/list에서 데이터들이 넘어갔는 지 확인

(2) getList를 외부가 아닌 내부에서 선언
외부에서 선언하는 것은 리터럴 상수만!

1
2
//getList = await axios.get('/api/board/list')
const result = await axios.get("/api/board/list");

(3) 1번에서 본 데이터 정보는 객체
list로 반환을 해주었지만 axios가 친절히 전송정보를 포함해서 객체로 만들어준다.

1
2
3
4
5
6
7
8
9
//getList.forEach(r => this.list.push({ writer: r.writer, title: r.title, content: r.content, regDate: r.regDate }))
result.data.forEach(r =>
  this.list.push({
    writer: r.writer,
    title: r.title,
    content: r.content,
    regDate: r.regDate
  })
);

(4) 최종 소스코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<script>
import axios from 'axios'
export default {
  data () {
    return {
      loading: false,
      list: [],
      error: null
    }
  },
  created () {
    this.getBoardList()
  },
  methods: {
    async getBoardList () {
      const result = await axios.get('/api/board/list')
      result.data.forEach(r => this.list.push({ writer: r.writer, title: r.title, content: r.content, reg_date: r.reg_date }))
    }
  }
}
</script>

cf)

1
const axios = require("axios").default;

require을 사용하는 것보다 import를 사용하는 것이 더 최신방법이다.

1
import axios from "axios";