首页 > 解决方案 > 为什么,当我进行 http 调用时,会收到一条错误消息,指出我的 url 不是字符串?

问题描述

配置文件包含一个对象:

var config = {
  uri: 'https://localhost:1234',
  postcodeTimeoutMillsecs: process.env.POSTCODE_TIMEOUT || 3000
};

module.exports = config;

我的 http 调用给了我一个错误,说我的必须是一个字符串,我很确定它是。console.log 告诉我我正在传递“http://localhost:1234”,这是我所期望的。

const fs = require('fs');
const config = require('../config/config');
const defaultHttp = require('axios');
const ono = require('ono');

exports.submitApplication = (data) => {
  console.log('config.uri=');
  console.log(config.uri);
  return new Promise((resolve, reject) => {
    let http = defaultHttp;

    http.options({
      method: 'post',
      url: config.uri,
      data: data,
      headers: {
          'Content-Type': 'application/json'
        },
    }).then(function (response) {
      resolve(response);
    }).catch(function (error) {
      var submissionErr;
      if (error.type === 'http') {
        // error received from DRSI Communicator
        submissionErr = ono({ status: error.code },
          'Submission failed - ' + error.toString() +
          ' - ' + (error.body.message || error.body.errors.join()));
        console.log(submissionErr);
      } else {
        submissionErr = ono({ status: 503 },
          'Submission failed - internal connectivity problem - ' + error.toString());
      }
      submissionErr.errorType = 'submission-failure';
      reject(submissionErr);
    });
  });
};

完整的错误消息是:消息:'提交失败 - 内部连接问题 - TypeError [ERR_INVALID_ARG_TYPE]:“url”参数必须是字符串类型。收到一个对象的实例'

知道我哪里出错了吗?

标签: javascripthttp

解决方案


看来您使用了错误的方法。

的参数列表http.options是:axios.options(url[, config])


http.options({
      method: 'post',
      url: config.uri,
      data: data,
      headers: {
          'Content-Type': 'application/json'
        },
    })

应该是

http({
      method: 'post',
      url: config.uri,
      data: data,
      headers: {
          'Content-Type': 'application/json'
        },
    })

或者

http.post(config.uri, data {
      headers: {
          'Content-Type': 'application/json'
        },
    })

来源: https ://github.com/axios/axios#axiosoptionsurl-config


推荐阅读