使用基本的身份验证和标头获取 Axios

时间:2021-04-24 21:35:06

标签: javascript reactjs api axios

我需要你的帮助: 我正在尝试访问需要用户名和密码的 API。 我是这样实现的:

  axios.get('https://example.net/rest/executions/1266026155/execution-log', {
    withCredentials: true,
    headers: {
      "Accept": "application/json",
      "Content-Type": "application/json"
    }
    },{
      auth: {
        username: "username12345",
        password: "12345678"
    }}).then(response => {
      if (response.status === 200) {
        console.log("All OK")
    }
})

但浏览器中的消息是:

xhr.js:177 GET https://example.net/rest/executions/1266026155/execution-log net::ERR_CERT_AUTHORITY_INVALID

在 Postman 中,我的尝试取得了令人满意的结果。 enter image description here enter image description here

非常感谢!

2 个答案:

答案 0 :(得分:0)

如果你想在服务器上发送一些数据,你应该使用 POST 方法,因为 GET 没有任何 bodydata。并且不要忘记导入

axios.post('https://example.net/rest/executions/1266026155/execution-log', {
    headers: {
      "Content-Type": "application/json"
    }
  },{
    body: {
      username: "username12345",
      password: "12345678"
  }}).then(response => {
    if (response.status === 200) {
      console.log("All OK")
  }
})

答案 1 :(得分:0)

我通过以下方式解决了这个问题:

const httpsAgent = new https.Agent({ rejectUnauthorized: false });
    const session_url = `/rest/executions/1266026155/execution-log`
    var username = 'myUserName'
    var password = 'myPass'
      
    axios.get(session_url, {
      withCredentials: true,
      auth: {
        username: username,
        password: password
      },
        httpsAgent: httpsAgent,
        headers: {
          "Accept": "application/json",
          "Content-Type": "application/json"
        }
      }).then( response => {
          if (response.status === 200) {
            console.log("Success")
          }
      }

但首先我必须配置代理: 我们有两个选择: a) 在 package.json 中添加参数

"proxy": 'https://myProxy.com/3000'

b) 使用 http-proxy-middleware 配置代理:

npm install --save-dev http-proxy-middleware

然后创建存档:setupProxy.js 在内容中:

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/oo/rest/executions',
    createProxyMiddleware({
      target: 'https://myProxy.com/3000',
      secure: false,
      changeOrigin: true,
    })
  );
};

然后我们运行项目:

npm start