question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

The correct way of POSTing data using Fetch to be used by Formidable

See original GitHub issue
// React redux saga simplified view
  const { loginEmail, loginPwd } = request.payload;
  
  let postLoginSubmitOptions = {
    method: "POST",
    headers: new Headers({'content-type': 'application/x-www-form-urlencoded'}),
    mode: 'no-cors',
    body: JSON.stringify({
      loginEmail: loginEmail,
      loginPwd: loginPwd
    })
  };

   const response = yield call(fetch, `http://www.example.com/register`, postLoginSubmitOptions);

// express simplified view

router.post('/register', function(req, res, next) {
  console.log('registering user');
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3333');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
  res.setHeader('Access-Control-Allow-Credentials', true);
  
  var form = new formidable.IncomingForm();

  form.parse(req, function(err, fields, files) {
    if(err){
      console.log(err);
    }
    console.log(`incoming fields via form parse`);
    console.log(fields); //{ '{"loginEmail":"my-email@gmail.com","loginPwd":"my-password"}': '' }
    console.log(fields.loginEmail); // undefined
  });

I’ve tried different Content-types, setting different Headers manually and also with “new Headers”, using new FormData() then data.append and body: data. Nothing works. I’ve enabled and disabled body-parser in app.js. The best I can do is getting this weird fields - { “string”: “empty_string” }. What am I doing wrong?

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
dantenovskicommented, Nov 10, 2017

I don’t know where exactly the problem was but tried encoding data differently and then it worked. Getting a nice parsed object now with formidable: { loginEmail: ‘dan@dan.com’, loginPwd: ‘asjdfkjsadlf’ }

function sendData(data) {
  const { loginEmail, loginPwd } = request.payload;
  const body = { loginEmail, loginPwd };
  var urlEncodedData = "";
  var urlEncodedDataPairs = [];
  var name;
 
  for(name in body) {
    urlEncodedDataPairs.push(encodeURIComponent(name) + '=' + encodeURIComponent(body[name]));
  }
  urlEncodedData = urlEncodedDataPairs.join('&').replace(/%20/g, '+');

  var httpHeaders = { 
    'Content-Type' : 'application/x-www-form-urlencoded', 
    'Accept' : 'application/json'
  }

  let postOptions = {
    method: 'post',
    headers: new Headers(httpHeaders),
    /*mode: 'no-cors',*/
    body: urlEncodedData
  };

  try {
    const response = yield call(fetch, `http://www.example.com/register`, postOptions);
    const data = yield call([response, response.json]);
    console.log(`data returned by fetch`);
    console.log(data);
    yield put({type: 'LOGIN_SUBMIT_RESPONSE', payload: data.message})
  } catch (e) {
    console.log(`error fetch post object`);
  }
}

Thanks everyone!

0reactions
tunnckoCorecommented, Nov 9, 2017

Oh yea. And also can try curl POST from terminal or at least https://www.hurl.it, so we can see if it is in the backend (formidable + express server) or on the frontend requesting logic.

Read more comments on GitHub >

github_iconTop Results From Across the Web

The correct way of POSTing data using Fetch to be ... - GitHub
React redux saga simplified view const { loginEmail, loginPwd } = request.payload; let postLoginSubmitOptions = { method: "POST", ...
Read more >
Using the Fetch API - MDN Web Docs
Supplying request options · Sending a request with credentials included · Uploading JSON data · Uploading a file · Uploading multiple files.
Read more >
Formidable Forms API for extendable WordPress forms
Go to 'Settings' → 'Actions & Notifications' and click on 'Send API Data' to add an API action. Insert this in the Notification...
Read more >
Uploading Files using Formidable in a Node.js Application
In this article, we will see how to use Formidable to handle multipart/form-data using Node.js, Express, and MongoDB.
Read more >
Using JavaScript Fetch with Formidablejs, Expressjs
I'm using Reactjs saga to send a post request using fetch. Also I'm trying to use formidable instead of usual body-parser. I'm getting...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found