如何从后端获得正确的响应?

时间:2020-02-03 09:53:23

标签: reactjs

我正在使用react-redux中的一个组件,这基本上是一种形式,而不是向后端发送新属性,并且我需要获取该响应(这是一个对象)并将其发送给我的reducer。邮递员中的响应是我想要的对象,其格式如下:

{
    "id_property": 50,
    "id_user": 1147040,
    "address_line1": "malagaga",
    "address_line2": "patata",
    "locality": "madrid",
    "region": "madrid",
    "postcode": 6000,
    "isDeleted": 0
}

但是当我尝试去调用该后端路由的sendForm函数时,我得到的响应是不确定的...这是触发bakcend调用的方法:

  async sendForm() {
    const token = localStorage.getItem("token");
    if (this.inputPhoto_propertyeRef.current?.files) {
      var photo_property = this.inputPhoto_propertyeRef.current.files[0];
    }
    const formData = new FormData();

    let {
      address_line1,
      address_line2,
      locality,
      region,
      postcode
    } = this.state;
    postcode = String(postcode);
    formData.append("photo_property", photo_property);
    formData.append("address_line1", address_line1);
    formData.append("address_line2", address_line2);
    formData.append("locality", locality);
    formData.append("region", region);
    formData.append("postcode", postcode);
    const results2 =  addProperty(token, formData) //this is the fetch tha goes to the backendroute and in postman returns the object
    console.log("SENT", results2);
    // this.props.addOneProperty(results2); //TODO envio result o property, pasarle la funcion desde el padre para cerrar el componente
    // this.props.toggleForm(); // function coming from the paren which dismount the component after sending
  }

这是后端路由,以防万一:

propertiesController.register = (request, response) => {
  const token = request.headers.authorization.replace("Bearer ", "");
  jwt.verify(token, myprivatekey);
  const { id_user } = jwtDecode(token);
  // const photo_property = request.file.filename;
  const {
    address_line1,
    address_line2,
    locality,
    region,
    postcode
  } = request.body;
  connection.query(
    `INSERT INTO property (id_user, address_line1, address_line2, locality ,region , postcode)
    VALUES ('${id_user}', '${address_line1}', '${address_line2}', '${locality}', '${region}','${postcode}') `,
    (err, results) => {
      console.log(results);
      if (err) {
        response.sendStatus(400);
        console.log(err);
      } else {
        connection.query(
          `SELECT * FROM property WHERE id_property = ${results.insertId}`,
          (err, results2) => {
            if (err) {
              response.sendStatus(400);
              console.log(err);
            }
            console.log(results2[0]);
            response.send(results2[0]);
          }
        );
      }
    }
  );
};
this is the call to the fetch:
import { IProperty } from "./../interfaces/IProperties";
import { IProfile } from "./../interfaces/IProfile";
import { IUser } from "../interfaces/IUser";

const host = "http://localhost:5000";

const myFetch = async ({
  path,
  method,
  json,
  token,
  formData
}: {
  path: string;
  method: string;
  json?: Object;
  token?: string;
  formData?: FormData;
}): Promise<any> => {
  let headers = new Headers();
  let body = undefined;
  if (token) {
    headers.set("Authorization", `Bearer ${token}`);
  }
  if (json) {
    headers.set("Content-Type", "application/json");
    body = JSON.stringify(json);
  } else if (formData) {
    body = formData;
  }

  const response = await fetch(host + path, {
    method: method,
    headers: headers,
    body: body
  });

  const res = await response.json();
  console.log(res);
  return res;


export const addProperty = async (token: any, formData: FormData):Promise<any> => {
  await myFetch({
    path: `/properties/register`,
    method: "post",
    token: token,
    formData: formData
  });
};
};

0 个答案:

没有答案