7

I'm using a basic fetch to obtain data from an express server that queries the data from a database. So I want to do a login system, i want to send the user/password from the input fields with the fetch request. so i can perform the logical check to see if password matches the data in the server. and respond with the result. Is it possible to do a fetch that can pass parameters?

Updated Code Below:

let fetchData = {
  method: "post",
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },

  body: JSON.stringify({
    username: this.state.user,
    password: this.state.password
  })
}

var fromServer = fetch('http://localhost:3000/', fetchData)
.then(function(response){
  if( !response.ok){
    throw Error (response.statusText);
  }
  return response.json();
})
.then(function(response) {
  console.log(response);
})
.catch(error => console.log("there was an error --> " + error));

Express function

app.post('/', function(req, res){
  var uname = req.body.username;
  var pw = req.body.password;
  console.log(uname);
  console.log(pw);
});

1 Answer 1

23

Of course you can!

Here is an example of Fetch using a POST request:

fetch("http://example.com/api/endpoint/", {
  method: "post",
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },

  //make sure to serialize your JSON body
  body: JSON.stringify({
    name: myName,
    password: myPassword
  })
})
.then( (response) => { 
   //do something awesome that makes the world a better place
});

I've answered this question before, check this for more details:

POST Request with Fetch API?

To process the request in Express, as mentioned in your comment assuming your express server is setup to parse body requests, you can do this:

app.post('/your/route', function(req, res) {
    var name= req.body.name;
    var password = req.body.password;

    // ...do your bidding with this data
});
Sign up to request clarification or add additional context in comments.

9 Comments

oh alright, and on the server side, do i just do a app.get? or app.post function?
Based on my example, and assuming you are working with ExpressJS, then yes app.post() is what you need to process that request.
ugh i feel like an idiot, i'm getting the post request but im not sure how to extract the data i'm passing over to express. in the app.post() function.
Parsing your data is a different issue, please follow this tutorial and specially pay attention to the body-parser section needed for JSON post requests: scotch.io/tutorials/…
I finally got it fully functional, it was the JSON parsing that was giving me some problems. Thank you so much for your patience and guidance!
|

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.