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

时间:2018-10-02 17:34:43

标签: javascript reactjs express axios ssr

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

- 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,也可以将其发送到react应用程序。

如何在axios中实际使用它?

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

1 个答案:

答案 0 :(得分:0)

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

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

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

相关问题