Javascript 如何使用axios在请求头中发送clientIP

Javascript 如何使用axios在请求头中发送clientIP,javascript,reactjs,express,axios,server-side-rendering,Javascript,Reactjs,Express,Axios,Server Side Rendering,我目前的项目结构是这样的 - MyApp - client - config - server - shared - src myReactApp.jsx - services api.js userService.js import api from './api' export default { fetchUserProfileDetails() { return api().get('/user

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

- MyApp
  - client
  - config
  - server
  - shared
    - src
        myReactApp.jsx
    - services
        api.js
        userService.js
import api from './api'
export default {
  fetchUserProfileDetails() {
    return api().get('/user/profile')
  }
}
我想在所有请求中将客户端的IP地址作为头发送到API服务器 我正在使用Axios向服务器发出请求 我的
api.js
文件包含以下内容

import axios from 'axios';

export default () =>
  axios.create({
    baseURL: config('apiUrl')
  });
在我的用户服务中,我这样调用api.js

- MyApp
  - client
  - config
  - server
  - shared
    - src
        myReactApp.jsx
    - services
        api.js
        userService.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地址 该应用程序基于react,并且使用
express
作为服务器端呈现 我能够使用
req.connection.socket.remoteAddress.split(“,”[0]
获取客户端的IP,并且还能够将其发送到react应用程序

如何在axios中实际使用它


我正在使用react的上下文API在react应用程序内部发送IP,这是从服务器向react应用程序发送信息的正确方法吗?

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

如果你没有客户端IP,你可以通过第三方应用程序或其他一些代码获得。看看这篇文章


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

我想你误解了我已经有了ip,我不明白的是如何将它注入axios,因为ip是使用上下文API发送到react应用程序的,它只初始化一次(在react应用程序开始时)然后将其保存在全局变量(如window或LocalStorage或Cookie)中,并在发出请求时更新
axios.defaults.headers.common
属性。此属性包含发送的标题。