我正在开发一个渐进式网络应用程序。我想缓存一个页面的两个版本
在离线使用的情况下,我需要检测请求是针对普通版本还是Ajax版本,以便我可以返回正确的数据。
学习 React.js 和 Node.js,并使用后端的 Express API 和前端的 React.js 制作一个简单的 CRUD 应用程序。我的 React.js 的 App.js 看起来像这样。
`import React, { Component } from 'react';
import './App.css';
import Rentals from './components/Rentals';
import Idpage from './components/Idpage';
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom';
class App extends Component {
render() {
return (
<div className="mainappdiv">
<Router>
<main>
<Route exact path="/" component={Home} />
<Route exact path="/rentals" component={Rentals} />
<Route path="/rentals/:propertyid" component={Idpage} />
</main>
</div>
</Router>
</div>
);
}}
export default App;
Run Code Online (Sandbox Code Playgroud)
我正在制作一个应用程序,当您访问 /rentals …
我将从 API 获取的数据打印到表中,但将行数值固定为小数时遇到一些困难。如果 API 中的行数据由数值组成,即 等10.0, 333, 8 or 100,则最终以十进制值呈现 -> 10.00, 333.00, 100.00。
我熟悉的函数.toFixed(2)在 React 中的运行方式与我以前在 javaScript 中编写它的方式不同。我认为我误导了 ES6 标准,但我不确定。如果我避免使用.toFixed(2).
这是我的代码示例rows.toFixed(2),但它的功能不佳:
class App extends React.Component
{
constructor()
{
super();
this.state = {
rows: [],
columns: []
}
}
componentDidMount()
{
fetch( "http://ickata.net/sag/api/staff/bonuses/" )
.then( function ( response )
{
return response.json();
} )
.then( data =>
{
this.setState( { rows: data.rows, columns: data.columns } );
} );
}
render()
{ …Run Code Online (Sandbox Code Playgroud) 我正在 React Web 应用程序中使用 Fetch 进行 API 调用(在另一个域上运行)。我收到错误以下错误。
从源“http://localhost:3000”获取“--------API URL---------”的访问已被 CORS 策略阻止:
对预检请求的响应不会通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明响应满足您的需求,请将请求模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。
我还在 Stack Overflow 上阅读了关于同一问题的几个答案,标题为“Access-Control-Allow-Origin”,但仍然不知道如何解决这个问题。我不想在 Chrome 中使用扩展程序或使用临时黑客来解决这个问题。请提出解决上述问题的标准方法。
我的代码如下所示:
{
return fetch('-----------API URL--------',
{ method:'GET',
mode: 'cors',
headers:{
'Access-Control-Allow-Origin':'*'
},
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson.ALLORDERSRX);
this.setState({
isLoading: false,
dataSource: responseJson.ALLORDERSRX,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
Run Code Online (Sandbox Code Playgroud) 我对更高级的 API 还很陌生,我正在尝试使用 fetch 向外部 API 发送 GET 请求,并使用 API 所有者详细说明的适当标头。
但是,我仍然收到 403 Forbidden 错误,并且标头实际上并未随请求一起发送,如 Chrome DevTools 显示的那样:
“正在显示临时标题”。
我正在使用 CORS 代理:https://cors-anywhere.herokuapp.com/,它可以处理其他更简单的 API 请求。
const proxy = 'https://cors-anywhere.herokuapp.com/';
const api = `${proxy}https://api-example.com`; // Obfuscated
// Generate the data
fetch(api, data = {}, {
credentials: "include",
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "Bearer eLrw3eXlljyFRjaul5UoYZLNgpUeapbXSFKmLc5SVaBgv8azUtoKn7B062PjbYoS",
"User-Agent": "any-name"
},
body: JSON.stringify(data)
})
.then(response => {
return response.text();
})
Run Code Online (Sandbox Code Playgroud)
API 请求在 Postman 中工作并使用curl,但在我的应用程序中,我收到 403 Forbidden 响应。正如还提到的,请求标头中仅显示临时标头;我没有设置任何标题。
任何帮助将非常感激。
我想通过fetch提交表单。控制器操作如下所示:
\n\n[HttpPost("new")]\n[ValidateAntiForgeryToken]\npublic JsonResult NewUser(NewUserViewModel user)\n{\n // code...\n}\nRun Code Online (Sandbox Code Playgroud)\n\n如您所见,我正在使用 ValidateAntiForgeryToken。\n在客户端,我发现此 jQuery 代码有效:
\n\n$.ajax({\n url: window.location.pathname,\n type: \'POST\',\n data: {\n Id: "1",\n UserName: "ajax",\n Password: "ajax",\n ConfirmPassword: "ajax",\n FullName: "ajax",\n Email: "ajax@ajax.is",\n Client: "ajax",\n Roles: ["ajax"],\n __RequestVerificationToken: document.querySelector(\'[name=__RequestVerificationToken]\').value\n },\n success: function (response) {\n alert(\'T\xc3\xb3kst\');\n },\n error: function () {\n alert(\'t\xc3\xb3kst ekki\');\n }\n});\nRun Code Online (Sandbox Code Playgroud)\n\n但我想使用 fetch API 所以我做了这个尝试:
\n\nlet response = await fetch(window.location.pathname, {\n method: \'POST\',\n body: {\n Id: "1",\n UserName: "fetch",\n Password: "fetch",\n ConfirmPassword: "fetch",\n FullName: "fetch",\n Email: …Run Code Online (Sandbox Code Playgroud) 问题是,我怎样才能摆脱调用 second fetch 300 次?或者有另一种方法可以做到这一点,我在做什么?另外,如何对第一个 api 进行有序(不想排序)调用,因为它们以混乱的异步方式来自 api?
for(let i=1;i<=300; i++) {
fetch(`example.api/incomes/${i}`) // should be returned 300 times
.then(response => {
if(response.ok) return response.json();
throw new Error(response.statusText);
})
.then(function handleData(data) {
return fetch('example.api') // should be returned 1 time
.then(response => {
if(response.ok) return response.json();
throw new Error(response.statusText);
})
})
.catch(function handleError(error) {
console.log("Error" +error);
});
};
Run Code Online (Sandbox Code Playgroud) 我正在执行 useEffect() 以使用 JSON 数据更新状态。但是,获取请求有时会失败,因此如果发生这种情况,我想重新执行 useEffect 钩子:
...
import React, {useState, useEffect} from 'react';
import {getJsonData} from './getJsonData';
const myApp = () => {
var ErrorFetchedChecker = false;
const [isLoading,setIsLoading] = useState(true);
const [data,setData] = useState(null);
const updateState = jsonData => {
setIsloading(false);
setData(jsonData);
};
useEffect(() => {
//console.log('EXECUTING');
getJsonData().then(
data => updateState(data),
error => {
Alert.alert('DATA FETCHING ERROR !', 'Refreshing ?...');
ErrorFetchedChecker = !ErrorFetchedChecker;
//console.log('LOG__FROM_CountriesTable: Executed');
},
);
}, [ErrorFetchedChecker]);//Shouldn't the change on this variable
//be enough to re-execute …Run Code Online (Sandbox Code Playgroud) I have created a react app using create-react-app and an express server using express-generator. My react app is running on http://localhost:3000 and my express server is running on http://localhost:8080. In my component I am making a POST fetch request to my express server, which is successfully running my express router code, returning a 200 response status code. However, the client console logs the following error and does not receive the response:
Proxy error: Could not proxy request /components/findAlbumArt from …Run Code Online (Sandbox Code Playgroud) I want to fetch data for every object in array passed as props (rootComments) and add the data to object properties:
useEffect(() => {
rootComments.map(rootComment => {
if (rootComment.kids) {
rootComment.kidsText = []
fetchKidsText(rootComment.kids)
}
})
console.log(rootComments)
rootComments.map(comment => console.log(Object.values(comment)))
}, [rootComments])
const fetchKidsText = async (ids) => {
await Promise.all(
ids.map(id => fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json?print=pretty`).then(response => response.json()).then(result => {
rootComments.map(comment => {
if (comment.id === result.parent) {
comment.kidsText = comment.kidsText.concat(result.text)
}
})
}))
);
}
Run Code Online (Sandbox Code Playgroud)
It seems like it …
fetch-api ×10
reactjs ×6
javascript ×5
node.js ×2
.net-core ×1
ajax ×1
api ×1
asp.net-mvc ×1
async-await ×1
cors ×1
express ×1
for-loop ×1
react-native ×1
tofixed ×1