简体   繁体   English

将表单传递标头反应到 api

[英]React form pass headers to api

I want to post a JSON to a external api from a react form.我想从反应形式将 JSON 发布到外部 api 。 the api needs headers (username:password) to access it. api 需要标头(用户名:密码)才能访问它。 I wanted to see how I would set up a form to take the inputs of a user and pass it as headers to the api then post some json.我想看看如何设置一个表单来获取用户的输入并将其作为标题传递给 api,然后发布一些 json。 I am able to do this with cURL but Im relatively new to react and this has been causing me some problems.我可以用 cURL 做到这一点,但我反应比较新,这给我带来了一些问题。

If you are using fetch to make API call you can do something like:如果您使用 fetch 进行 API 调用,您可以执行以下操作:

function signIn(username, password, body) {
    const options = {
        method: method,
        headers: new Headers({username, password}),
        mode: 'no-cors'
    };

    options.body = JSON.stringify(body);

    fetch(url, options)
    .then(response => response.json())
    .then(data => console.log(data));
}

You might wanna read more about the same here你可能想在这里阅读更多关于相同的内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM