前提
expressでapiを作成 (localhost:4000で起動)
reactでaxiosを使ってapiを叩く
困っていること
Proxyを設定した時と設定せずにfull pathでapiを叩いた時で返ってくるデータが違う
参考コード
APIはすごくシンプルで簡素な物
js:API
1app.get("/", (req, res) => { 2 return res.json({ msg: "rootです。" }); 3});
Full Pathで叩いてみる(途中省略)
js
1axios.get("http://localhost:4000").then((res) => { 2 console.log(res.data); 3 }); 4 5// 結果 6{msg: 'rootです。'}
Package.jsonにproxyを設定して省略する
json:Package.json
1"proxy": "http://localhost:4000"
js
1// Proxyを設定したので省略して叩く 2axios.get("/").then((res) => { 3 console.log(res.data); 4 });
js
1// 結果 2 3<!DOCTYPE html> 4<html lang="en"> 5 <head> 6 <meta charset="utf-8" /> 7 <link rel="icon" href="/favicon.ico" /> 8 <meta name="viewport" content="width=device-width, initial-scale=1" /> 9 <meta name="theme-color" content="#000000" /> 10 <meta 11 name="description" 12 content="Web site created using create-react-app" 13 /> 14 <link rel="apple-touch-icon" href="/logo192.png" /> 15 <!-- 16 manifest.json provides metadata used when your web app is installed on a 17 user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/ 18 --> 19 <link rel="manifest" href="/manifest.json" /> 20 <!-- 21 Notice the use of in the tags above. 22 It will be replaced with the URL of the `public` folder during the build. 23 Only files inside the `public` folder can be referenced from the HTML. 24 25 Unlike "/favicon.ico" or "favicon.ico", "/favicon.ico" will 26 work correctly both with client-side routing and a non-root public URL. 27 Learn how to configure a non-root public URL by running `npm run build`. 28 --> 29 <title>React App</title> 30 <script defer src="/static/js/bundle.js"></script></head> 31 <body> 32 <noscript>You need to enable JavaScript to run this app.</noscript> 33 <div id="root"></div> 34 <!-- 35 This HTML file is a template. 36 If you open it directly in the browser, you will see an empty page. 37 38 You can add webfonts, meta tags, or analytics to this file. 39 The build step will place the bundled scripts into the <body> tag. 40 41 To begin the development, run `npm start` or `yarn start`. 42 To create a production bundle, use `npm run build` or `yarn build`. 43 --> 44 </body> 45</html>
考えていること
status自体は200なので叩けているとは思うのですが、なぜ返ってくる内容が違うのでしょうか?
proxyを設定してjsonデータを扱うにはどうすればよいか教えていただきたいです。
あなたの回答
tips
プレビュー