首页 > 解决方案 > 如何使用 axios 在请求标头中发送 clientIP

问题描述

我目前的项目结构是这样的

- MyApp
  - client
  - config
  - server
  - shared
    - src
        myReactApp.jsx
    - services
        api.js
        userService.js

我想在所有请求中将客户端的 IP 地址作为标头发送到 API 服务器 我正在使用 Axios 向服务器发出请求 我的api.js文件有这个

import axios from 'axios';

export default () =>
  axios.create({
    baseURL: config('apiUrl')
  });

在我的用户服务中,我像这样调用 api.js

import api from './api'
export default {
  fetchUserProfileDetails() {
    return api().get('/user/profile')
  }
}

然后我在我的组件中使用它作为

import UserService from '../userService'

...

componentDidMount () {
  UserService.fetchUserProfileDetails()
  .then(results => {
    // do stuff with the results
  })
}

我想知道的是,当我进行这种设置时,如何在每个请求中发送客户端的 IP 地址 该应用程序是基于反应的,并且也是服务器端渲染的,express用作服务器我能够使用req.connection.socket.remoteAddress.split(",")[0]和获取客户端的 IP我也能够将其发送到反应应用程序中。

如何在 axios 中实际使用它?

我正在使用反应的上下文 API 在反应应用程序中发送 IP,这是将信息从服务器发送到反应应用程序的正确方法吗?

标签: javascriptreactjsexpressaxiosserver-side-rendering

解决方案


如果您已经可以在代码中获取客户端的 IP,则可以设置 Axios 的默认标头,就像axios.defaults.headers.common['CLIENT_IP'] = clientIP.

如果您没有客户端 IP,您可以通过第三方应用程序获得,其他一些代码。看看这篇文章https://ourcodeworld.com/articles/read/257/how-to-get-the-client-ip-address-with-javascript-only

但要获得它,最好使用您的服务器。在 Express 中,它只是req.ip.


推荐阅读