我目前的项目结构是这样的
- 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地址,当我有这种设置时,应用程序是基于react的,也是服务器端呈现的,使用express作为服务器,我能够使用req.connection.socket.remoteAddress.split(",")[0]获得客户端的IP,也能够将其发送到react应用程序中。
如何在axios中实际使用它?
我正在使用react的上下文API在react应用程序内部发送IP,这是将信息从服务器发送到react应用程序的正确方式吗?
发布于 2018-10-03 02:16:34
如果您已经可以在代码中获取客户端的IP,则可以设置Axios的默认标头,就像axios.defaults.headers.common['CLIENT_IP'] = clientIP一样。
如果您没有客户端IP,您可以使用第三方应用程序other和一些代码来获取。只需看看这篇文章https://ourcodeworld.com/articles/read/257/how-to-get-the-client-ip-address-with-javascript-only
但要获得它,最好使用您的服务器。在Express中,它只是req.ip。
https://stackoverflow.com/questions/52613527
复制相似问题