我正在POST使用 API 从前端发出请求fetch。但当我在 Firefox 中尝试时,它不起作用。在 Chrome 中工作正常。
这就是我正在尝试做的事情。
const handleSubmit = async event => {
try {
await fetch(`https://api.example.net/api/route?slug=example`, {
method: 'post',
headers: {
'Content-Type': 'application/json',
'x-api-key': /* API KEY*/
},
body: JSON.stringify({
name,
email
})
})
.then(response => console.log(response))
.catch(err => console.log(err));
} catch (error) {
console.log(error);
}
};
Run Code Online (Sandbox Code Playgroud) 我遇到的问题是我有一个带有访问密钥的 API,但我不知道如何使用该 API 访问密钥在组件内设置标头。我在下面的示例中使用默认的获取随机用户 API,但我想知道应该如何以及在哪里添加带有访问密钥的标头?
import React from 'react';
export default class FetchRandomUser extends React.Component {
async componentDidMount() {
const url = "https://api.randomuser.me/"
const response = await fetch(url)
const data = await response.json();
this.setState({ person: data.results[0], loading: false })
}
render() {
return <div>
{this.state.loading || !this.state.person ? (<div>Loading...</div>) : (<div>{this.state.person.name.first}</div>)}
</div>
}
}
Run Code Online (Sandbox Code Playgroud) 我很好奇为什么人们在 React 中使用 axios 而不是 fetch api 来发出 API 请求。Axios 相对于 Fetch 有什么优势还是只是个人选择?
希望就此获得一些不同的意见。
谢谢
我正在 Express 服务器上使用 Node 'form-data' 模块来构建对来自客户端浏览器的 fetch 请求的 multipart/form-data 响应(这也是使用 fetch 的多部分,但在服务器上使用 multer 可以很好地接收到)服务器)。当服务器发回表单数据响应时,我在收到响应时在获取客户端收到错误 - “无法将内容解析为 FormData。”(本机 FormData)(注意:这与不解析多部分的 Express 解析器不同,这是浏览器上的本机获取客户端不解析节点表单数据)我在服务器响应或客户端响应处理中做错了什么?
在服务器上:
const formdata = require('form-data')
app.post(req,res,next) {
// ... process the request and construct form-data response...//
var form = new formdata();
form.append("serverResponse", "Reply from server to fetch request from client")
res.end(form.getBuffer())
}
Run Code Online (Sandbox Code Playgroud)
在客户处
//... send request to server which has no problem, but returncannot decode the response as FormData
return fetch( pRequest )
.then(response => {
return response.formData() //***this throws …Run Code Online (Sandbox Code Playgroud) javascript multipartform-data xmlhttprequest form-data fetch-api
使用 new Headers() 对象为获取设置标头有什么区别,如下所示。
const headers = new Headers()
headers.set('User','Bob')
Run Code Online (Sandbox Code Playgroud)
与使用更少的代码分配所需的标头并且不使用新的 Header() 类相比。
const headers = { User: 'Bob'}
Run Code Online (Sandbox Code Playgroud)
在 JavaScript 中执行 a 时fetch。
如果两者都获得相似的结果,那么在获取数据时哪一种是最佳实践?
我正在使用 Nextjs + Strapi 构建一个新闻网站,因为新闻网站是高度动态的,需要每分钟推送更新,所以我无法使用,getStaticProps因为即使使用增量静态再生,这种在构建上获取数据的方法也没有任何意义,此外该网站必须具有高级搜索和用户帐户,用户可以在其中个性化他们想要阅读的新闻类别。
我能够用来getServerProps在布局中获取主菜单数据(新闻类别),我创建了动态路由,但是当涉及到获取属于它的新闻文章(单一类别)时,我找不到任何明确的文档。
我尝试在./pages/api文件夹中创建一个外部方法,以使用as变量getCategoryData.js从外部 api(Strapi 后端)获取单个类别数据,我能够正确获取数据,但我尝试了多种方法将类别数据分配给页面主体方法内部,它没有成功并且返回未定义。axioscategory.slugconst category
这正是我在单一类别页面中所做的:
./pages/category/[slug]/index.js
import { useRouter } from 'next/router'
import DefaultLayout from "../../../components/layouts/default";
import { getCategory } from "../../api/getCategoryData";
const CategoryArticles = ({ menuItems }) => {
const router = useRouter()
const { slug } = router.query
const category = getCategoryData(slug);
console.log(category) // here returns undefined !!!
return (
<DefaultLayout menuItems={ menuItems }>
<div> { category.name } </div>
</DefaultLayout> …Run Code Online (Sandbox Code Playgroud) 我正在努力从 js 中的 http fetch 获取实际结果数据。我可以使用 XMLHttpRequest 来完成此操作,但我更愿意使用获取。我一直在尝试从这样的获取请求中获取结果:fetch('https://api.website.net/?);
我知道您需要分配一个 then 函数,但我尝试过的任何方法都不起作用,我不断获得更多的承诺对象,但没有结果。我模糊地理解,一旦它解析,您需要分配一个 .then 函数,但我真的不知道如何做到这一点。
(这是在浏览器js中而不是节点中)
我在浏览器中运行这段代码
<html>
<script type="module">
console.log("working");
var url = "https://slack.com/api/chat.postMessage";
var auth_token = "xoxb-2B"; //Your Bot's auth token
var body = {channel: "ses", text: "testing app"}
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
headers: {
"Authorization": "Bearer " + auth_token,
"Content-Type" : "application/json"
},
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // …Run Code Online (Sandbox Code Playgroud) 有没有办法发送 HTTP 请求并fetch()告诉它不要自动设置标头?我试图让它发送一个没有 的请求Content-Type,我可以让它发送一个空标头
Content-Type:
Run Code Online (Sandbox Code Playgroud)
像这样
fetch('http://localhost:8000/', {
method: 'POST',
headers: {
'Content-Type': ''
},
body: 'some data'
});
Run Code Online (Sandbox Code Playgroud)
但我可以让它完全不包含该行吗?
我正在尝试让我的网络应用程序的登录流程正常工作。该 Web 应用程序是使用 Nuxt 3 作为在 http://localhost:3000 上运行的前端 (SPA) 和 Laravel 作为在 http://localhost 上运行的后端编写的。
因为 Nuxt 3 使用 fetch API,而 axios 目前不适用于 Nuxt 3,所以我试图让 Laravel Sanctum 的登录流程和 fetch API 正常工作。
我在前端 Nuxt 应用程序上使用可组合函数调用 Laravel 后端,如下所示:
export const useLogin = async (email, password) => {
const config = useRuntimeConfig()
const tokenResponse = await $fetch(config.baseURL + '/sanctum/csrf-cookie', {
method: 'GET',
credentials: 'include'
})
const token = getCookie('XSRF-TOKEN') …Run Code Online (Sandbox Code Playgroud) fetch-api ×10
javascript ×8
reactjs ×4
next.js ×2
access-token ×1
axios ×1
content-type ×1
firefox ×1
form-data ×1
http ×1
http-headers ×1
laravel ×1
nuxtjs3 ×1
slack-api ×1
strapi ×1