사용환경 : Linux, Ubuntu, Vue.js 3, vue-cli, axios - post, php
Vue-cli port : 8081 PHP Apache server port : 8080
Vue.js 3 에서 axios 를 이용해 php 에 데이터를 송신 하는 방법을 포스팅하도록 하겠습니다.
3일 째 이거 만지다가 어쩌다 됐습니다. 억울..
[버전은 상관없지만] @vue/cli 4.5.15 에서 적용하였습니다.
■ 1. Vue-cli project 설정 1/2
/src/views/Account/AxiosTest.vue
디렉터리 구조
제가 form 을 이용해 post data 를 송신 할 Vue 페이지 는 위와 같습니다.
AxiosTest.vue => input 태그 2개로, id 와 password를 전달하려고 합니다.
1. Template
<template> <div> <form action="" @submit="checkForm"> <input type="text" name="id" v-model="idValue" /> <input type="password" name="password" v-model="passwordValue" /> <button type="submit">submit</button> </form> </div> </template>
2. script
<script> import axios from "axios"; export default { data() { return { idValue: "", passwordValue: "", }; }, methods: { async checkForm(e) { e.preventDefault(); let idValue = this.idValue; let passwordValue = this.passwordValue; await axios .post("/api/loginCheck", { id: idValue, password: passwordValue }) .then(function (response) { // handle success console.log("success"); console.log(response); }) .catch(function (error) { // handle error console.log(error); }) .then(function () { // always executed }); }, }, }; </script>
■ 1. Vue-cli project 설정 2/2
vue.config.js
vue.config.js
프로젝트의 root 경로에 vue.config.js 파일을 없으신 분들은 생성해주시고 아래의 내용을 복붙해주세요.
vue.config.js
module.exports = { devServer: { proxy: { "/api": { target: "http://localhost:8080/", }, }, }, };
■ 3. php
Apache 서버 를 사용하신다면, 8080포트 로 구동 중이실겁니다. (본인의 포트 에 맞게 설정해주세요)
/var/www/html/ 경로에 /api 폴더 를 생성해주세요. 이곳에 axios 의 data 를 수신할 php 파일 을 생성할겁니다.
이렇게 생성하였습니다. (자유롭게 생성해주세요. 보통 /api 라고 많이 생성합니다.
/api/loginCheck.php
<?php // header의 요청을 수락하는 php 설정들. 안해주면 데이터를 못받는 경우가 생김 header('Access-Control-Allow-Origin:*'); header("Access-Control-Allow-Credentials", "true"); header('Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'); header('Access-Control-Allow-Methods:GET,POST,PUT,DELETE,OPTIONS'); $data = json_decode(file_get_contents('php://input'), true); // 반복문으로 데이터 출력
■ 결과
개발자 - 네트워크
data
콘솔 화면
감격스럽게도 200 통신 성공 결과가 출력되었고,
php 에서 $data 는 array 의 타입이기 때문에 출력 결과(response ) 가 array 로 출력되었습니다.
■ 1차 수정
- 기존에 params 를 넘겨줘서 자꾸 데이터가 array로 출력이 되었습니다.
params를 없앤 모습
- 기존 : data(=params객체) : jsonStyleValues - 변경 : { jsonStyleValues list}
* POST method 에서는 params 를 넘겨주면 안된다.
참고
Sending Axios parameters with a POST request in PHP – ZeroWP
Using a library like Axios to create complex AJAX requests is simple and easy. Of course, we can use `fetch` but still, I prefer Axios because of the many options it has, which is lightweight, well documented, and stable. Recently I tried to use it by crea
zerowp.com
Configuration Reference | Vue CLI
Configuration Reference Global CLI Config Some global configurations for @vue/cli, such as your preferred package manager and your locally saved presets, are stored in a JSON file named .vuerc in your home directory. You can edit this file directly with yo
cli.vuejs.org
https://coderedirect.com/questions/43570/axios-get-from-local-php-just-returns-code-instead-of-executing
Axios GET from local PHP just returns code instead of executing - Code Redirect
The API I am trying to access has disabled CORS so I need to request on the server side. Utilizing React and Axios I am making a get request to the local php file which should execute cURL but am j...
coderedirect.com
덕분에 3일동안 axios 와 http , proxy , 등에 대해 많이 공부할 수 있었습니다.