⛳
fastify × axiosでgetしようとしたら詰まった
環境
TypeScript => 4.93
react => 18.2.0
fastify => 4.10.0
axios => 1.1.3
困ったこと
以下のコードを書いたら'Network Error'が返ってきました。
statuscodeは200で通っているが、値が返ってこない。サーバーサイドでURLを手動で動かしたら値は表示されるし、curlコマンドでも返ってくるが、フロント側のボタンを押したときだけエラーになる。
surver/index.ts
import fastify from 'fastify'
const server = fastify()
server.get('/ping', async (request, reply) => {
return 'pong\n'
})
server.get('/', async (request, reply) => {
return { hello: 'world' }
})
server.get('/users', async (request, reply) => {
return JSON.stringify({ hello: 'users' })
})
server.listen({ port: 8080 }, (err, address) => {
if (err) {
console.error(err)
process.exit(1)
}
console.log(`Server listening at ${address}`)
})
クライアント側はこちら
signup.tsx
import * as React from 'react'
import { createTheme, ThemeProvider } from '@mui/material/styles'
import type { FormEvent } from 'react'
import axios from 'axios'
// const axios = require('axios').default
const theme = createTheme()
export default function SignUp() {
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault()
const data = new FormData(e.currentTarget)
console.log({
email: data.get('email'),
password: data.get('password'),
})
const email: string = data.get('email') as string
const password: string = data.get('password') as string
console.log(typeof email)
//FormDataEntryValue型をstring型に変える。
const getIp = async () => {
try {
const result = await axios.get('http://127.0.0.1:8080/')
console.log(result)
} catch (error) {
console.log('error!!')
}
}
getIp()
axios
.get('http://localhost:8080?ID=12345')
.then(function (response) {
// handle success
console.log(response)
})
.catch(function (error) {
// handle error
console.log(error)
})
.then(function () {
// always executed
})
axios
.get(`http://localhost:8080/`)
.then(function (response) {
console.log('ok')
})
.catch(function (error) {
console.log(error)
})
結論
CORSが書かれてなかった。@fastify/corsを入れて、公式と同じように記入する。
server/index.tsx
import Fastify from 'fastify'
import cors from '@fastify/cors'
const fastify = Fastify()
await fastify.register(cors, {
// put your options here
})
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})
await fastify.listen({ port: 8080 })
こんなエラーが出る。tsconfig.jsonをいじってもできず、面倒そうなのでasyncで囲う。
surver/index.tsx
import Fastify from 'fastify'
import cors from '@fastify/cors'
const fastify = Fastify()
;(async () => {
await fastify.register(cors, {
// put your options here
})
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})
await fastify.listen({ port: 8080 })
})()
これで解決!fastifyは情報がまだ少ないので頑張ろう
参考文献
Discussion