gad74
gad74

Reputation: 145

How do I handle a question mark being sent through a url?

I am using axios to send some strings to my database. The current things im sending are

1: Header -> the value can be anything such as "Who is Michael Scott?"
2: Body -> the value can be anything such as "Why do people quote Michael Scott a lot?"

The axios command im using is:

  axios.post(`/post/create/${Header}/${Body}`).then(result => {
    alert("Your post has been added!")
    console.log("Posted")
  }).catch(function (error) {
      // Output error
      console.log(error);
  });

The output in the url (address bar) is:

http://my_ip_here:3000/api/v1/post/create/Who%20is%20Michael%20Scott?/Why%20do%20people%20quote%20Michael%20Scott%20a%20lot?/

This ends up giving me a 404 because of the question mark. My question is, how do I handle question marks inside strings that are passed as a url parameter?

If it helps, Im using React.js, Axios, and Mysql.

Upvotes: 1

Views: 1508

Answers (2)

M Danil Rafiqi
M Danil Rafiqi

Reputation: 584

i think if you use this url : /post/create/${Header}/${Body} is not best practice. if you use post method i suggest you to pass your data in body.

axios.post(`/post/create/`, {header: Header, body:Body}).then(result => {
    alert("Your post has been added!")
    console.log("Posted")
}).catch(function (error) {
    // Output error
    console.log(error);
});

Upvotes: 0

Bruno Smaldone
Bruno Smaldone

Reputation: 210

You need to URL encode them.

Before passing their value to axios, make sure you run encodeURIComponent(myString).

Maybe this:

axios.post(`/post/create/${encodeURIComponent(Header)}/${encodeURIComponent(Body)}`).then(result => {...}

Upvotes: 3

Related Questions