1

我正在使用 axios 和 API 来获取页面的 HTML,编辑 HTML,然后通过对 API 的 POST 请求将其放回。我成功地检索和编辑了 HTML,但我不知道如何将其放回/更改网页的 HTML。

我尝试使用 PUT 请求而不是 POST 请求,但出现 405 错误,表明网页不允许使用 PUT 方法。

axios.get(url, {
  auth: {
    username: USERNAME,
    password: PASSWORD
  },
  headers: {
    'Content-Type': 'application/json'
  }
})
.then( (response) => {
  version = response.data.version.number;
  body = response.data.body.storage.value;

  // takes the body HTML and formats all the links
  newBody = middleware.formatLinks(body);

  data = {
    "type": "page",
    'version': {'number': version + 1},
    'body': {
      'storage': {
        'value': newBody,
        'representation': 'storage'
      }
    }
  }

  // put the body HTML back into the page
  axios.post(url, {
    data: {
      "type": "page",
      'version': {'number': version + 1},
      'body': {
        'storage': {
          'value': newBody,
          'representation': 'storage'
        }
      }
    }
  }, { 
    auth: {
    username: USERNAME,
    password: PASSWORD
    },
    headers: {
      'Content-Type': 'application/json'
    }
  })
  .then( (response) => {
    console.log(response.data);  
  })
  .catch( (error) => {
    console.log(error);
  })
})
.catch( (error) => {
  console.log(error);
})

我希望该页面现在可以使用我喜欢的所有链接进行更新。但是页面没有变化。当我console.log(response.data)发出 post 请求后,输出是一个字符串newBody,当我期望它是 JSON 对象时

data: {
  'type': 'page',
  'version': {'number': version + 1},
  'body': {
    'storage': {
      'value': newBody,
      'representation': 'storage'
    }
  }
}
4

2 回答 2

1

正如我在@Aman Raj 的回答中的评论中提到的,我的代码在 python 中工作,但将其翻译为 nodejs 给我带来了问题。所以我通过使用 python-shell 包在 nodejs 中调用我的 python 脚本来规避我的问题。

let {PythonShell} = require('python-shell');
...
const formatLinks = (id) => {
    let options = {
      mode: 'text',
      pythonOptions: ['-u'], // get print results in real-time
      scriptPath: './python/', // path to my python scripts

      // pass in the page id, username, and password to API request
      args: [id, USERNAME, PASSWORD] 
    };

    PythonShell.run('script.py', options, (err, results) => {
      if (err) throw err;
      // results is an array consisting of messages collected during execution
      console.log('results: %j', results);
    });
}
于 2019-07-10T21:07:25.033 回答
0

你的代码看起来不错。您可能正在访问不支持对其进行编辑的 API。

超文本传输​​协议 (HTTP) 405 Method Not Allowed 响应状态码表示请求方法为服务器已知但目标资源不支持。

于 2019-07-10T20:18:48.217 回答