使用JavaScript Fetch和Formidablejs,Expressjs

时间:2017-11-08 02:32:46

标签: javascript forms http fetch formidable

我正在使用Reactjs saga来使用fetch发送帖子请求。此外,我正在尝试使用强大而不是通常的身体解析器。我得到了奇怪的解析问题。我做错了什么?

// saga simplified piece of code
const { loginEmail, loginPwd } = request.payload;

let postLoginSubmitOptions = {
  method: "POST",
  headers: {
    'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
    'Content-Type' : 'application/x-www-form-urlencoded'
  },
  body: JSON.stringify({
    loginEmail: loginEmail,
    loginPwd: loginPwd
  })
};

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

// expressjs side, simplified view

router.post('/register', function(req, res, next) {
  console.log('registering user');

  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
  });

  }

2 个答案:

答案 0 :(得分:0)

将内容类型传递为json

let postLoginSubmitOptions = {
  method: "POST",
  headers: new Headers({'content-type': 'application/json'}),
  body: JSON.stringify({
    loginEmail: loginEmail,
    loginPwd: loginPwd
  })
};

答案 1 :(得分:0)

我不知道问题究竟在哪里,但尝试以不同的方式编码数据然后才有效。现在使用强大的{ 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`);
  }
}

谢谢大家!