ReactJS如何使用axios发送HTTPS请求(而不是HTTP)

14

我正在尝试使用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)
})

有人能帮我将这个请求转换为https请求吗?


1
如果您的服务器拥有https证书,则应自动默认使用该证书。 - Agney
1个回答

11

所有的URL都有两个部分

  1. 域名 - http://yourdomain.com
  2. 路径 - /path-to-your-endpoint

1. 使用默认域名

axios中,如果您只指定了path,它会默认使用地址栏中的域名。

例如,下面的代码将调用地址栏中的任何域,并将此路径附加到其中。如果域是http,则您的API请求将是一个http调用,如果域是https,则API请求将是一个https调用。通常,localhosthttp,您将在localhost进行http调用。

axios.post('/api/login/authentication', {

2. 指定包含域名的完整URL

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

axios.post('https://yourdomain.com/api/login/authentication', {

2. 使用axios的baseURL选项

您也可以在axios中设置baseURL

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)
});

感谢您的回答。我遇到了以下错误:无法加载资源:发生SSL错误,无法建立与服务器的安全连接。XMLHttpRequest无法加载https://localhost:3000/api/login/authentication,因为访问控制检查。这可能是另一个问题还是与我发送请求的方式有关? - jim
你能在浏览器中打开那个 HTTPS URL 吗?你有收到任何 SSL 证书错误吗?你确定端口号是正确的吗(它不能与 HTTP 的端口号相同)? - Thilo
2
你面临的错误与请求无关。1. localhost通常只支持http。2. 要启用https,您需要在服务器上设置证书。 - Dinesh Pandiyan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接