I have the following simple PHP page:
<?php
echo 'done';
When I send a Javascript fetch request to that URL, I can inspect the response in the browser's dev tools and see that it returns the string 'done'.
Here is the request:
const response = await fetch(url, {
credentials: 'include'
});
On the other hand, if I start a session, the response is blank:
<?php
session_start();
echo 'done';
In both cases, the request headers are exactly the same, the response headers are exactly the same and the HTTP code is 200. It also works correctly if I manually go to that URL in the browser. It only fails specifically with fetch requests.
Note, I have display_errors and display_startup_errors set to On and nothing is outputted to the browser and nothing is logged in the log file either.
This behavior is because of a bug with Chromium that the devs have decided they "WontFix" and have stopped answering comments.
In order to get it to work, you need to manually read response.text() or response.json():
const response = await fetch(url);
const text = await response.text();
Once you do that, the response body will show up in your dev tools. If not, it will appear as if the response was empty, even if it wasn't.
You can use async with Await
Asyn function getData(url){
const response = await fetch(url);
const data = await response.json();
Console.log(data).
}
You can change the .json() to text()
Related
I requesting the server(written in Node.js) using "fetch-api" function of javascript. I want to make multiple request to the server When the user clicks a button.
Is there such a way in JavaScript ?
When the server responds. Then the second request Send.
And when second response come.
Third request send and so on...
Please help me . Thanks in advance!
the fetch function returns a promise.
you need to await it like so:
await fetch('http://test.com/1');
await fetch('http://test.com/2');
await fetch('http://test.com/3');
you can also access the responses like so:
const res1 = await fetch('http://test.com/1');
const data1 = await res1.json();
if (data1.foo == '123') {
await fetch('http://test.com/2');
await fetch('http://test.com/3');
}
when i debug this code in to chrome console then its not show any output or alert! please help me to complete this code! i need to get read my read.txt file text in to console.log....
the code was i try one is shows below.
function loadText() {
fetch('C:\Windows\Temp\read.txt')
.then(function(response){
return response.text();
})
.then(function(data){
console.log(data);
alert(data)
})
.catch(function(error){
console.log(error);
alert(data)
})
}
Try below code and indicate your directory like below
async function fetchText() {
let response = await fetch('../demo.txt');
console.log(response.status); // 200
console.log(response.statusText); // OK
if (response.status === 200) {
let data = await response.text();
console.log(data);
// handle data
}
}
fetchText();
This seems like a duplicate of this issue - AJAX request to local file system not working in Chrome?
The problems are the same, however you are using the fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) not an XMLHttp request (https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)
When i run loadText i get the following error:-
Fetch API cannot load . URL scheme must be "http" or "https" for CORS request.
You cannot make requests to the filesystem in Chrome. However you can disable Chrome security using flags (--allow-file-access-from-files)
see - Allow Google Chrome to use XMLHttpRequest to load a URL from a local file however this is not advised.
You will also need to update your path in the fetch function by prefixing with file:/// this tells it to look in the file system, and changed the protocol from http or https.
So I have this link I generated with GSX2JSON, and it looks like this: http://gsx2json.com/api?id=136PcbZppJfCH1vbE_j4X803umxv0_EWEg5Tjxnvvp7o&sheet=1. Now, I want to fetch the data into a variable, and so I used this code:
async function deetdeet(){
let response = await fetch('http://gsx2json.com/api?id=136PcbZppJfCH1vbE_j4X803umxv0_EWEg5Tjxnvvp7o&sheet=1');
if (response.ok) {
let json = await response.json();
console.log(json)
console.log("hyeet")
} else {
alert("Err: " + response.status);
}
}
deetdeet()
Sadly, this doesn't seem to return the JSON that is shown in the API, and I can't figure out why. I've tried using fetch() and even .getJSON() from JQUERY all to no avail. Is there an issue with my code, or the API I'm using?
Browsers block mixed content to protect against various attacks on users, so fetching HTTP resources from a HTTPS context will be blocked.
Look into proxying your request with a HTTPS API-Wrapper or using an API supporting HTTPS.
Make sure if you are running your site off HTTPS, that all fetch() requests are being handled through HTTPS as well.
I am trying to intercept a request, change the method to post and pass Data.
...
page.on('request', request => {
payload = {...}
var data = {'method': 'POST', 'postData': payload
request.continue(data)
});
await page.goto(url_post_product)
The problem is the URL url_post_product doesn't return any body, the status_code is a 302 so I always have a TimeoutError: Navigation Timeout Exceeded.
I think I need to know the location reponse and redirected it bur nothing happens when I try to incertecept the reponse.
page.on('response', response => {console.log(response.status())});
I know the request and posted data is well formed.
EDIT
it's seems to a chromium bug:
Puppeteer GitHub bug
I'm trying to do webcrawling using fetch on React Native. This is what I'm doing:
const response = fetch(
url,
{
body : post_data ? post_data : undefined, // must match 'Content-Type' header
cache : 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
headers : headers,
method : post_data ? 'POST' : 'GET', // *GET, POST, PUT, DELETE, etc.
redirect : redirect ? 'follow' : 'manual', // *manual, follow, error. TODO: is manual the right keyword?
referrer : 'no-referrer', // *client, no-referrer
}
);
const http = await response;
const header = http.headers;
const html = http.text();
console.log(html);
When I print header, I can see the headers. When I print html, this is what I see:
{ _40: 0, _65: 0, _55: null, _72: null }
What am I possibly doing wrong? I thought one await was necessary, but if I change to:
const http = await response;
const header = await http.headers;
const html = await http.text();
console.log(html);
then I can see the HTML. But as I've read, await makes the execution pause and resolves the Promise. So why should I need the two extra awaits below await response?
Taking a step back, await accepts a promise as its argument. Looking at the docs for fetch. fetch() returns a promise. response.headers is not a promise. response.text() returns a promise.
Given all of that, await response.headers is not necessary, but your other two are.
As for why response.text() returns a promise, the critical piece is that the response promise resolves as soon as the request starts getting data back, which is before the response data has already been received. This means that await response waits to know "did the server response, and if so with what status code/header, andawait response.text()` waits for the actual data that the server sends.
Getting the response is one promise, while reading it's content is a second promise. That's why you need to await twice.
Equivalent without async/await would be:
fetch("/url")
.then((response) => response.text() /* check response status and etc */)
.then((response) => console.log(response) /* actual response text /*);
Fetch returns a Response object, which is a stream that does not actually contain the response content. You have to call one of the methods to read the stream and return the actual content.
For example:
const response = await fetch( /* your parameters */ );
const responseText = await response.text();