Javascript 对本地文件的提取请求不起作用
我试图在本地文件中发出请求,但我不知道何时尝试在我的计算机上显示错误。是否可以提取项目中的文件Javascript 对本地文件的提取请求不起作用,javascript,reactjs,fetch-api,Javascript,Reactjs,Fetch Api,我试图在本地文件中发出请求,但我不知道何时尝试在我的计算机上显示错误。是否可以提取项目中的文件 // Option 1 componentDidMount() { fetch('./movies.json') .then(res => res.json()) .then((data) => { console.log(data) }); } error: Uncaught (in promise) SyntaxErro
// Option 1
componentDidMount() {
fetch('./movies.json')
.then(res => res.json())
.then((data) => {
console.log(data)
});
}
error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 at App.js: 10 --> .then(res => res.json())
// Option 2
componentDidMount() {
fetch('./movies.json', {
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then( res => res.json())
.then((data) => {
console.log(data);
});
}
error1: GET http://localhost:3000/movies.json 404 (Not Found) at App.js:15 --> fetch('./movies.json', {
error2: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 at App.js: 10 --> .then(res => res.json())
// This works
componentDidMount() {
fetch('https://facebook.github.io/react-native/movies.json')
.then( res => res.json() )
.then( (data) => {
console.log(data)
})
}
//选项1
componentDidMount(){
获取('./movies.json')
.then(res=>res.json())
。然后((数据)=>{
console.log(数据)
});
}
错误:未捕获(承诺中)语法错误:意外标记<位于App.js:10-->位置0的JSON中。然后(res=>res.JSON())
//选择2
componentDidMount(){
获取('./movies.json'{
标题:{
“内容类型”:“应用程序/json”,
“接受”:“应用程序/json”
}
})
.then(res=>res.json())
。然后((数据)=>{
控制台日志(数据);
});
}
错误1:获取http://localhost:3000/movies.json 404(未找到)位于App.js:15-->获取('./movies.json'{
错误2:未捕获(承诺中)语法错误:意外标记<位于App.js:10-->位置0的JSON中。然后(res=>res.JSON())
//这很有效
componentDidMount(){
取('https://facebook.github.io/react-native/movies.json')
.then(res=>res.json())
。然后((数据)=>{
console.log(数据)
})
}
您正在尝试使用fetch命令为静态文件提供服务,该命令本质上要求服务器为该文件提供服务。要解决此问题,您可以使用一些选项。我将概述两种最常用的建议:
- 使用Node.js和类似的工具来托管您自己的服务器,为您要获取的文件提供服务。虽然此过程可能需要更多的精力和时间,但它肯定更具可定制性,是了解和理解从后端获取如何工作的好方法
- 使用类似于轻松设置一个非常简单的服务器以在本地网络上为您的文件提供服务的方法。使用此方法,您对使用上述web服务器所能做的事情几乎没有控制权,但您可以快速轻松地对web应用程序进行原型化。然而,我怀疑是否有办法将此方法应用到生产中
最后,还有其他选项,您可以在线上传一个或多个文件并从外部URL获取它们,但这可能不是最佳策略。您的JSON文件需要由服务器提供服务,因此您需要express服务器(或任何其他)。在本例中,我们使用的是express 注意:您也可以下载 App.js文件
import React, { Component } from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
componentDidMount() {
const myHeaders = new Headers({
"Content-Type": "application/json",
Accept: "application/json"
});
fetch("http://localhost:5000/movie", {
headers: myHeaders,
})
.then(response => {
console.log(response);
return response.json();
})
.then(data => {
console.log(data);
this.setState({ data });
});
}
render() {
return <div className="App">{JSON.stringify(this.state.data)}</div>;
}
}
export default App;
我的方法是使用设置一个快速本地服务器,然后运行(免费层可以)并将你的应用指向它创建的url。这样做的好处是,你可以轻松地在iOS模拟器或Android模拟器以及未连接到计算机的设备上测试你的抓取。此外,你还可以将url发送给测试你的应用的人。当然,需要有一种方法让他们手动输入该url,这样应用程序才能正常运行无法将其设置为获取端点。请尝试将json文件放置在公用文件夹中,如下所示: public/movies.json 然后使用
fetch('./movies.json')
或
我以前也遇到过同样的问题。当我将json文件放在公用文件夹中时,问题就解决了。
使用fetch时,React通常会读取公用文件夹中的资产/资源文件。您可以将json文件放在公用文件夹中。在React组件中,您可以使用userEffect()。这种情况下不需要Express.js
React.useEffect(() => {
fetch("./views/util/cities.json")
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
});
我用一种非常简单的方法实现了这一点——实际上不需要express/webserver。只需执行以下操作:
import data from '../assets/data.json';
并像这样使用json数据(如果是JsonArray):
data.map(电影
在
App.js
或其他扩展React.Component
的类中执行此操作,假设我有以下文件test.html
<html>
<head>
<meta charset="UTF-8" />
</head>
<body>
<script>
var depdata;
depdata = fetch("test1.geojson")
.then((data) => {
return data;
});
depdata.then(function(data) {console.log(data)})
</script>
</body>
</html>
当我关注firefox上的错误时,我得到了以下解释
CORS请求只能使用HTTPS URL方案,但请求指定的URL是另一种类型。如果URL使用文件:///URL指定本地文件,则通常会发生这种情况
要解决此问题,只需确保在发出涉及COR的请求时使用HTTPS URL,例如XMLHttpRequest、获取API、Web字体(@font-face)、WebGL纹理和XSL样式表
因此,据我所知,我们只需要通过HTTP
访问test.html。解决这个问题最直接的方法是在终端中使用python简单HTTP服务器
> cd directory of the project.
> python3 -m http.server 8000 --bind 127.0.0.1
然后在浏览器中:
http://localhost:8000/test.html
我遇到了相同的错误,我在代码中做了两个更改以消除错误。首先,您不需要express server来为您的文件提供服务,您可以从create react app目录中的公用文件夹中的本地json文件中读取数据
const getData=()=>{
fetch('data.json',{
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}
)
.then(function(response){
console.log(response)
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
}
useEffect(()=>{
getData()
},[])
首先,正如上面一些答案中所建议的,确保json文件位于公用文件夹中,并且fetch函数中的path参数如上所述是正确的。
其次,如图所示设置标题。从我的获取调用中删除标题部分仍然会导致此错误。解决此问题的简单方法是使用live server extension(如果使用vs代码)解决此错误
Unexpected token < in JSON at position 0
JSON中位置0处的意外标记<
来自请求失败时返回的HTML文件。第一个元素(位于位置0)HTML文件的导入通常是一个“您将无法这样获取它,因为您的本地服务器不知道什么是
movies.json
。我建议您使用import
,或者添加一个路由来为API中的文件提供服务。从第二个错误GET来看,该文件似乎不存在。”http://localhost:3000/movies.json 404(未找到)
。我们无法告诉您文件的位置。。。
http://localhost:8000/test.html
const getData=()=>{
fetch('data.json',{
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}
)
.then(function(response){
console.log(response)
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});
}
useEffect(()=>{
getData()
},[])
Unexpected token < in JSON at position 0