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

问题描述 投票:0回答:1

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

- 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作为服务器的服务器端渲染我能够使用客户端的IP获取req.connection.socket.remoteAddress.split(",")[0],我也能够将其发送到反应应用程序中。

如何在axios中实际使用它?

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

javascript reactjs express axios ssr
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.