728x90

axios는

지원하는 브라우저가 더 많고 

에러핸들링이 좋고

자동으로 데이터가 json형태로 되어 넘어간다

Automatic JSON data transformation

As we saw earlier, Axios automatically stringifies the data when sending requests (though you can override the default behavior and define a different transformation mechanism). When using fetch(), however, you’d have to do it manually.

Compare:

// axios
axios.get('https://api.github.com/orgs/axios')
  .then(response => {
    console.log(response.data);
  }, error => {
    console.log(error);
  });

// fetch()
fetch('https://api.github.com/orgs/axios')
  .then(response => response.json())    // one extra step
  .then(data => {
    console.log(data) 
  })
  .catch(error => console.error(error));

fetch는 직접 json화를 해줘야하지만

지원하는 브라우저 문제 등을 충분히  해결할 수 있다.

 

 

결론

Axios는 대부분의 HTTP통신 요구사항을 위해 컴팩트 패키지로 사용하기 쉬운 API를 제공한다.

하지만 fetch()메소드를 사용해서도 Axios 라이브러리의 주요기능을 완벽하게 재현할 수 있다.

는 글

https://blog.logrocket.com/axios-vs-fetch-best-http-requests/

 

Axios vs. fetch(): Which is best for making HTTP requests? - LogRocket Blog

Axios is not always an ideal solution; depending on your needs, there are sometimes better options for making HTTP requests. The Fetch API is one of them.

blog.logrocket.com

 

728x90
728x90

 


 


 

728x90
728x90

어제 학원사람들이라 하면서 깨달은 점이랑 정리못했던 서버구축 내용 써보자~

서버 구축 코드는 이거 보면서 함요 https://blckchainetc.tistory.com/m/332

 

[119일차] 블록체인 네트워크 웹소켓 http ws 웹서버 구축

P2P (Peer to Peer) 구현 방법 -> WebSocket -> socket.io = 웹소켓으로 웹으로 구성할 때 필수적인 구성을 미리 만들어 놓은 패키지  이전 node.js chatting을 만들 때 사용함  기본 기능 외 여러가지 기능이..

blckchainetc.tistory.com

 

p2p 구현하기 위해서 서버 구축을 해보자!

(p2p peer to peer 노드, 참여자들간의 통신을 의미한다고 생각하면 됨!)

ws, 웹소켓쓸거임

 

블록체인은 대략적으로 크게 두개의 포트가 빌요한데

1. 중앙서버! 

서버- 클라이언트 

걍 작업, 블록생성한거 보여주는 데라고 이해함

(블록생성하고 작업하는 서버라고 생각했는데 검증과 생성을 서버 나눠서 따로 할 수도 있겠네.. 아니다 서버 안나누고 실행만 분리해도 될거같고..)

2. 노드끼리 통신

 

웹서버 구축의 기초 작업! 셋팅 시작!!

1. server - client http 서버 만들기

npm i express로 설치

 

//HTTP Server 초기화,P2P Server 초기화, 지갑 초기화
//(사용자와 노드간의 통신)

//client http 서버 만들기 express 사용
const express = require("express");
const app= express();
const port = process.env.PORT ||3000
const bodyParser = require('body-parser')
//블럭 가져오기
//현재 있는 블록들 가져와주는 함수
const {getBlocks} = require('./chainedBlock.js');

//바디파서 써서 json으로 볼예정임
app.use(bodyParser.json());
//blocks버튼임
app.get('/blocks',(req,res)=>{
    res.send(getBlocks())
})
app.listen(port,()=>{
    console.log(`server start port ${port}`)
    
})

서버 3000 잘 열렸고 

 

포트 변경도 해봄

(여기서 PORT변수로 명령어로 변수 값 변경한다고 생각하면 됨)

다시 3000으로 돌아와서

 

서버에 블록 가져와 보자!!

 

chainedBlock.js 에 만들었던 (이전 글에 코드 있음요)

blocks를 가져올거야. 

(chainedBlock.js에서 module.export로 getBlocks내보내기 해서 가져올 수 있음)

//현재가지고 있는 블록가져오는 함수
const {getBlocks} = require('./chainedBlock.js');

이걸로 함수 호출해서 기존 블록가져옴

app.get('/blocks',(req,res)=>{
    res.send(getBlocks())
})

 

 

이제 get잘되는지 확인해보자!

curl -X GET http://localhost:3000/blocks
curl http://localhost:3000/blocks -X GET   (요것도 가능!)

아 근데 curl 자체 의미하는게

"curl은 사용자 상호 작용 없이 작동하도록 설계된 서버에서 또는 서버로 데이터를 전송하기 위한 명령줄 유틸리티입니다"

그니까 명령어로 포스트맨,ARC같은거 안써도 볼 수 있는건데

나는 썼다

advanced REST client 확장자 설치해서 사용했음

 

 

여기서도 확인할 수 있겠죠

 

 

아!! 참고로 get post 알다가도 모르게 계속 헷갈렸는데 

다시금 이해함

 

post는 데이터 전송하고

get은  정보를 요청하는거! 그니까 버튼같은 역할이라고 생각하면 쉬움

이거 누르면 원하는 정보들이 보여지는거임

 

 

/blocks로  get으로 요청했으니까 

기존 제네시스 블록이 보이지

 

 

 

그럼 데이터 전송, 즉 추가하는 거 해보자

 

블록을 추가하는 것을 웹서버에서 해보자고

 

post로 해야겠지

 

//HTTP Server 초기화,P2P Server 초기화, 지갑 초기화
//(사용자와 노드간의 통신)

//client http 서버 만들기 express 사용
const express = require("express");
const app= express();
const port = process.env.PORT ||3000
const bodyParser = require('body-parser')
//블럭 가져오기
const {getBlocks,nextBlock} = require('./chainedBlock.js');
const {addBlock}= require('./checkValidBlock')

//바디파서 써서 json으로 볼예정임
app.use(bodyParser.json());
//blocks버튼임
app.get('/blocks',(req,res)=>{
    res.send(getBlocks())
})
app.listen(port,()=>{
    console.log(`server start port ${port}`)
    
})
//블록추가하기
app.post('/mineBlock',(req,res)=>{
    const data = req.body.data || []
    console.log(data)
    const block = nextBlock(data)
   addBlock(block)
   res.send(getBlocks())
})

바디데이터(아니면 빈배열)를 데이터로 이름 짓고 

다음블록생성하는 함수에 데이터 넣음

 

데이터 넣은 걸 block으로 이름 짓고 

그 블록을 블록배열에 추가한다!

(참고로 addBlock함수는 checkedValied에서 가져왔음)

그리고 getBlock함수로 지금 블록배열다 보이게 한다.

 

data로 변수 설정해서 "data"라고 하는 거임

 

 

이제 get요청인 blocks버튼 눌러보면요

배열에 추가된거 볼 수 있다.

 

 

 

 

좀 헷갈리는 거는 

chainedBlock에도 addBlock함수가 있고

checkedValid에도 addBlock함수가 있음

 

그래서

그냥 연결하는 체인드블록에서걸로

addBlock가져와서 쓰니까 오류났었음

블록구조가 유효한지 확인해야돼서 그런것도 있는데

둘 차이가 넣는 값이 다른거같은데 

bodyDate여서 그런가...흠 여긴 잘 모르겠군!

728x90
728x90

앞에 올린 글

노드js express로 로그인 창만들때 

헷갈렸던 거

 

 

app.get   app.post 차이

 

 

그니까(내가 본 설명글 / 이것도 있음)

get은 /주소 보이는 방식이라서 /뒤에 주소 써주는데로 이동하고 띄우고 get써서 경로이동할 수 있게 하고
post는 주소 안보여주는 방식. 눈에 보이지 않는 주소요청 받아처리함. post에서는 서버에서 처리할 일 요청할 수도 있고 데이터를 전송할 수도 있음

 

앞에 쓴 글

코드 보면

html에서

post 로 form 써서 

메인페이지랑

로그인페이지 둘다 name 데이터 전송해서 썼어

 

app.js 에서는 경로 이동 쉽게 할려고 get쓰고

post로 정보 받아서 썼구나

오호...

 

res.send 특징 

res.write 써야돼? 여러개 쓰고 싶으면?

 

https://fierycoding.tistory.com/18

 

  • res.send(body), res.send(status, body) : 클라이언트에 응답을 보냄. 상태 코드는 옵션. 기본 콘텐츠 타입은 text/html이므로 text/plain을 보내려면 res.set(‘Content-Type’, ‘text/plain’)을 먼저 호출 해야한다. JSON을 보낼거면 res.json을 쓰자.

여기 req res 메서드 개념 잘 정리 되어있다!!

 

사실 정말 가려운 곳 못긁었는데 차차 해보면서 알아가도록 ..

 

 

키 값

name vaule 차이가 뭐야

넘길 때 왜 name 넘겨주면 value는 왜 쓰지..  

 

 

 

 

Value = The value attribute specifies the value of an element.

Name = name is only to post form data. The name definies what the name of the attribute will be as soon as the form is submitted. So if you want to read this attribute later you will find it under the "name" in the POST or GET Request. Whereas the id is used to adress a field or element in javascript or css.

 설명굿

 

아하!!

맞다

 

이분 오타내심 value

요거네 name이 전달되고 value는 입력 태그의 초기값

 

HTML - input태그와 그 속성 type, value, name - 입력태그 (1)

HTML - input태그와 그 속성 type, value, name 입력태그 (1)  오늘은 input태그와 그 속성 type, value, name에 대해서 알아 보도록 하겠습니다. 태그 기초부터 알아보기 전에 압타나 스튜디오를 직접 설치 하.

yangbari.tistory.com

오호라 헷갈렸어

728x90

+ Recent posts