javascript - 如何使用 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,这是将信息从服务器发送到反应应用程序的正确方法吗?
解决方案
如果您已经可以在代码中获取客户端的 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
.
推荐阅读
- sql - 在具有附加条件的树中查找实体的后代(PostgreSQL)
- git - 我分支的代码没有合并回主分支,为什么不呢?
- python-3.x - 如何通过 celery 配置为 RabbitMQ 中的队列分配优先级?
- java - 数字平方和
- javascript - 我用 create-react-app 创建了一个项目。在我的 Windows pc 上,但是当尝试在命令行上运行 npm start 时,它显示此错误。请帮助我
- regex - 某些特殊字符仅在它们前面有转义字符时才允许使用
- android - 如何在我当前的注册代码旁边验证 CheckBox?- 安卓工作室
- javascript - 如何忽略未使用参数的类型检查?
- javascript - ReferenceError:未定义名字 - JavaScript
- javascript - 如果出现 pg 错误,表示服务器关闭