反应 Post 未显示 Header

React Post not showing Header

修正: 我一下子改变了一些东西,所以我真的不知道是什么解决了我的问题,但基本上: - API 需要 int 或 long,我正在发送 String.. parseInt 解决了它。 我最初声明了一个数据 object:

const [data, setData] = useState({

})

有了我稍后要发送的所有值(以及正确的数据类型!如果我不确定,null 似乎很适合初始化)。 -另一个问题是我在 POST 请求之前将所有数据合并到一个钩子中,因为它是异步的……这是个坏主意。 -最后,但最重要的是,这可能就是问题所在(感谢 EntiendoNull 和 JMadelaine),我将数据初始化为 [] 而不是 {},所以我在数组内部发送了一个 object。因此当我 POST 时 API 中的 JSON parse error: Cannot deserialize instance of 消息。 .-------------------------------------------- ---------------------------------------------- ------------------------------.

我遇到了 post 请求无法正常工作的问题。

基本上header不对,应该是{"content-type": "application/json"} 但相反,它是一个空 object。 这是我执行 POST:

的地方
const [data, setData] = useState([]);
    const createMission = async (e) => {
        setData({
            ...data,
            nom:state.missionName,
            id_client:state.currentClientKey,
            id_consultant:state.currentConsultantId,
            id_manager:1,
            id_ro:state.currentROKey,
            id_rc:state.currentRCKey,
            detail:state.missionDescription,
            adresse:state.adresse,
            frequence_eval:6,
            date_debut:state.startDate,
            date_fin:state.endDate,
            metier:state.metier
        });
        let headers = {
          headers: {'Content-Type': 'application/json'}
        };
        axios.post('http://localhost:8080/mission',data,{"headers" : headers})
        .then(res => {
            console.log(res);
        });

我的导航器控制台上res的内容如下:

   {…}
    ​
    config: Object { url: "http://localhost:8080/mission", method: "post", data: "{\"nom\":\"\",\"id_consultant\":null,\"id_manager\":1,\"detail\":\"\",\"adresse\":\"\",\"frequence_eval\":6,\"date_debut\":null,\"date_fin\":null,\"metier\":null}", … }
    ​
    data: ""
    ​
    headers: Object {  }
    ​
    request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }
    ​
    status: 200
    ​
    statusText: ""
    ​
    <prototype>: Object { … }

数据发送正常,我返回 200 状态,但如您所见,header 中有一个空的 object,数据是一个空字符串 "".

有趣的是,我在另一个组件上做了几乎完全相同的事情,而且效果很好: 在这种情况下,我什至没有指定 headers.

const createClient = async (e) => {
        axios.post('http://localhost:8080/client', {nom:state.nomClient})
        .then(res => {
            console.log(res);
        });
    };

这是日志:

 {…}
    ​
    config: Object { url: "http://localhost:8080/client", method: "post", data: "{\"nom\":\"aze\"}", … }
    ​
    data: Object { id: 372, nom: "aze" }
    ​
    headers: Object { "content-type": "application/json" }
    ​
    request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }
    ​
    status: 200
    ​
    statusText: ""
    ​
    <prototype>: Object { … }

和API一样,都是@RequestBody。 为使命而来:

@PostMapping
    public Mission addMission (@RequestBody MissionBean missionBean){
        Optional<Client> optionalClient = clientRepository.findById(missionBean.id_client);
        Optional<Consultant> optionalConsultant = consultantRepository.findById(missionBean.id_consultant);
        Optional<Utilisateur> optionalManager = utilisateurRepository.findById(missionBean.id_manager);
        Optional<Utilisateur> optionalRo = utilisateurRepository.findById(missionBean.id_ro);
        Optional<Utilisateur> optionalRc = utilisateurRepository.findById(missionBean.id_rc);
        if (optionalClient.isPresent() && optionalManager.isPresent() && optionalConsultant.isPresent() && optionalRo.isPresent() && optionalRc.isPresent()){
            Mission newMission = new Mission(
                    missionBean.nom,
                    optionalClient.get(),
                    optionalConsultant.get(),
                    optionalManager.get(),
                    optionalRo.get(),
                    optionalRc.get(),
                    missionBean.detail,
                    missionBean.adresse,
                    missionBean.frequence_eval,
                    missionBean.date_debut,
                    missionBean.date_fin,
                    missionBean.metier
            );
            missionRepository.save(newMission);
            return newMission;
        }
        return null;
    }

这里是给客户的(第二个例子很好用):

@PostMapping
    public Client addClient (@RequestBody Client client){
        clientRepository.save(client);
        Critere critere = new Critere(client,"Ponctualité",true);
        Critere critere2 = new Critere(client,"Assiduité",true);
        Critere critere3 = new Critere(client,"Intégration",true);
        critereRepository.save(critere);
        critereRepository.save(critere2);
        critereRepository.save(critere3);
        return client;
    }

我已经尝试了很多不同的方法来指定 headers,但它仍然不起作用。 请求运行良好(200),但数据未被理解 API 方面,没有 header,因此数据为空字符串,我对此很陌生,所以我被卡住了这里。当我检查我的数据库时,没有添加任何新内容。

编辑: 每次发出请求时,我都会从 API 收到一条消息:

2020-02-22 22:19:39.737  WARN 4205 --- [nio-8080-exec-7] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `com.evalside.project.beans.MissionBean` out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.evalside.project.beans.MissionBean` out of START_ARRAY token
 at [Source: (PushbackInputStream); line: 1, column: 1]]

也许这有助于指出问题

Edit2:我的一些值应该是 int,但以 String 的形式出现(刚刚注意到)要解决这个问题,然后再试一次

你可能不想那样使用你的状态。

首先,你的data state的初始值应该是一个object(根据你指向的是什么类型和值以后再说)。最好从一开始就明确你的意图:)

const [data, setData] = useState({});

其次,按照您的方式更新状态可能会导致问题。 考虑改用 setDate(prevState => { // your logic })

Third,从您显示的代码来看,按照您的方式设置状态然后将其提供给您的 axios.post 请求没有多大意义。还是有其他原因导致这些值在您的请求中使用之前存储在某种状态中?其中大部分似乎已经存储在其他 state 中,对吧?

相反,您可以声明一个 const 来保存这些值:

const myData = {
    nom:state.missionName,
    id_client:state.currentClientKey,
    id_consultant:state.currentConsultantId,
    id_manager:1,
    id_ro:state.currentROKey,
    id_rc:state.currentRCKey,
    detail:state.missionDescription,
    adresse:state.adresse,
    frequence_eval:6,
    date_debut:state.startDate,
    date_fin:state.endDate,
    metier:state.metier
}

通常,一旦您的副作用完成并且您收到了回复,您就可能想要更新这样的状态。

第四,你确实声明了一个headers-对象;

let headers = {
    headers: {'Content-Type': 'application/json'}
};

所以在你的 axios-request 中这样做:

axios.post('http://localhost:8080/mission', data, headers);

而不是这个:

axios.post('http://localhost:8080/mission',data,{"headers" : headers})

感谢您的帮助

First, the initial value of your data state should be an object (according do what kind of type and value you point it to be later). Better be clear with your intentions from start :)

const [data, setData] = useState({});

实际上是这样,我这样写:const [data, setData] = useState([]); 不是 {}。

我开始上钩了,是的,我还没有养成正确的习惯,我会尝试更频繁地使用 setDate(prevState => { // your logic })

我有几个组件都将一些值提升到这个组件中,最终会发出 post 请求,这就是为什么它对所有状态和传递的数据有点混乱,但我已经尝试过很多方法,我已经尝试过简单地做:

const data = {name:myName, date:myDate etc..}
(...)
axios.post('url', data, headers)

我在 API 中遗漏了其他事情,将其添加到 post,也许它会有所帮助 ;)