【问题标题】:How to post a url如何发布网址
【发布时间】:2021-03-04 16:24:04
【问题描述】:

我正在尝试将图像转换为 url,然后使用 axios.post 将其发布到数据库,如下所示:

   this.setState({
      file: URL.createObjectURL(event.target.files[0])
    })

然后像这样发布:

 axios
    .post(`http://localhost:4000/items/${this.state.file}

我的模型是这样的:

let items = new schema ({
  img: String
})

还有我的后期控制器:

router.post('/:urlImg', function (req, res) {
  let b= new items ({
    imageProof: req.params.urlImg
  })

错误基本上是 POST 'url' 404 (Not Found):

xhr.js:184 POST http://localhost:4000/items/blob:http://localhost:3000/9045e921-4e7f-4541-8329-0b9cd65814c6 404 (Not Found)

但是要注意的是,如果我使用的是简单的 url,例如 www.google.com,它可以工作。但是,我不能使用 https:// 有谁知道我该如何解决这个问题?还有其他方法来存储和显示图像吗?

【问题讨论】:

  • 按 F12,单击控制台选项卡,查看您的浏览器是否给出任何错误消息。
  • 是的,我已经用它更新了问题:

标签: node.js reactjs axios mern


【解决方案1】:

您可以简单地对您的图片网址进行 url 编码,如下所示。当您只传递 url 而不首先对其进行编码时,它会形成一个无效的 url,其中包含中间的 https。所以你必须在通过之前对其进行编码

axios
    .post(`http://localhost:4000/items/${encodeURIComponent(this.state.file)}

或者

不要将其作为 url 参数发送,而是将其作为正文参数发送

axios.post('/user', {
    urlImg: "http://your/image/url"
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

对于第二种方法,您可能需要更改后端以便从请求对象中提取参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 2012-06-01
    • 2011-11-24
    • 2016-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多