reactjs 使用 axios 发出 https(不是 http)请求

jim*_*jim 8 https reactjs axios

我正在尝试使用 axios 向服务器发出 https 请求。大多数关于 axios 的教程都指定了如何发出 http 请求。每当用户登录时,我都会发出请求。这是我目前的要求:

axios.post('/api/login/authentication', {
  email: email,
  password: password
})
.then(response => {
  this.props.history.push('/MainPage')
})
.catch(error => {
  console.log(error)
})
Run Code Online (Sandbox Code Playgroud)

谁能帮我将其转换为 https 请求?

Din*_*yan 5

所有 URL 都有两部分

  1. 领域 - http://yourdomain.com
  2. 小路 - /path-to-your-endpoint

1.使用默认域

在 中axios,如果您仅指定path,则默认情况下它将使用地址栏中的域。

例如,下面的代码将调用地址栏中的任何域并将此路径附加到它。如果域是http,则您的 api 请求将是http调用;如果域是https,则 api 请求将是https调用。通常localhosthttp,您将http拨打localhost.

axios.post('/api/login/authentication', {
Run Code Online (Sandbox Code Playgroud)

2. 指定带域的完整 URL

另一方面,您可以将完整 URL 传递给 axios 请求,https默认情况下您将进行调用。

axios.post('https://yourdomain.com/api/login/authentication', {
Run Code Online (Sandbox Code Playgroud)

2. 使用 axios baseURL 选项

也可以baseURL在axios中设置

axios({
  method: 'post',
  baseURL: 'https://yourdomain.com/api/',
  url: '/login/authentication',
  data: {
    email: email,
    password: password
  }
}).then(response => {
  this.props.history.push('/MainPage')
})
.catch(error => {
  console.log(error)
});
Run Code Online (Sandbox Code Playgroud)

  • 您遇到的错误与请求无关。1. localhost 通常只是 `http`。2. 要启用“https”,您需要在服务器中设置证书。 (2认同)