1

Hello i'm trying to make a get request in react

with JQuery i used to do something like this

$.get("Run",{ pr: "takeData", name: "Bob"}, function (o) {
                   console.log(o)
             
            });

i tried doing something like this

fetch("https://localhost:44347/Run?{
      pr:"takeData",
    name:"Bob"
    }) .then( res => res.text())
   .then((data) => {
        console.log(data);
   });

but id didn't worked,instead i had to do it like this

fetch("https://localhost:44347/Run?pr=takeData&name='Bob'") .then( res => res.text())
   .then((data) => {
        console.log(data);
   });

and it worked, but i can't figure out how to pass the "pr" and the "name" parameters without having to type them directly in the url can someone help me?

2

2 Answers 2

2

You can create URL and URLSearchParams objects to create your request without writing the fields in the URL by hand.

var url = new URL("https://localhost:44347/Run");
url.search = new URLSearchParams({ pr: "takeData", name: "Bob"});
fetch(url).then( res => res.text())
       .then((data) => {
         console.log(data);
     });
Sign up to request clarification or add additional context in comments.

1 Comment

Please at least look for duplicates for such obvious questions...
0

You can use templates literals for that see this : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Here is an exemple :

const myString = `https://localhost:44347/Run?pr=${varPr}&name=${varName}`

Another way is to add strings like this :

const myString = "https://localhost:44347/Run?pr=" + varPr + "&name=" + varName

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.