How to post a url

Viewed 92

I am trying to convert an image to a url and then post it to a database using axios.post like this:

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

and then posting it like so:

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

my model is this:

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

and my post controller:

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

the error is basically 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)

however the thing to note is if I am using a simple url such as www.google.com, it works. however, I can't use https:// does anyone know how I can resolve this problem? Is there some other way to store and display an image?

1 Answers

You can simply url encode your image url as follow. When you just pass the url without encoding it first it forms a invalid url which contains https in the middle. So you have to encode it before passing

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

Or

Instead of sending it as a url parameter send it as a body parameter

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

For 2nd approach you might want to change the backend in order to extract the parameter from the request object.

Related