Suppose the client does this
fetch('example.json', {
headers: {
'Accept': 'application/json',
'Accept-Encoding': 'gzip',
'Cache-control': 'no-cache'
},
method: 'GET'
}).then()
And the server worker does this
self.addEventListener('fetch', (event:any) => {
let request = event.request
if (request.method !== 'GET') return
event.respondWith( caches.match(request)
.then( cachedResponse => {
if (cachedResponse) return cachedResponse
return caches.open(RUNTIME)
.then(cache => fetch(request)
.then(response => cache.put(request, response.clone())
.then(() => response) ))
}))
})
Can I assume caches.match(request) will figure out 'Cache-control': 'no-cache' and just bail out regardless what is stored in the service worker cache?
Feel free to correct me but after googling some more I found this
https://bugs.chromium.org/p/chromium/issues/detail?id=451664#
When I test console.log('SW :', request.headers.get('Cache-control')) the headers seem to be stript out.
I am slowly getting why some browser vendors are hesitant for service workers, it makes the whole caching unintuitive and browser cache already was unintuitive in the first place.
Related
I'm working on a project which has rails api as a back-end and angular as a front end. In one particular point I need to make a text/plain call. Even though I set the content-type to 'text/plain', HttpClient tries to parse payload to json. I can't figure out why it behaves like that.
Rails back-end:
def getTranslations
render plain: 'some plain text'
end
Angular Client:
headers = new HttpHeaders({
"Content-Type": "text/plain",
"Accept": "text/plain"
});
this.http.get<any>('http://localhost:3000/getTranslations', { headers: this.headers })
.map((res:Response) => {
console.log(res);
return res.text()
})
.subscribe(
res => {
console.log(res);
},
err => {
console.log(err);
}
)
Response:
"Http failure during parsing for http://localhost:3000/getTranslations"
Unexpected token s in JSON
Thanks.
After looking at angular.io documentation I have found the answer.
Instead of making request by http.get I have changed the method call to
this.http.get('http://localhost:3000/getTranslations', { responseType: 'text'} )
.map((res:string) => {
console.log(res);
return res
})
.subscribe(
res => {
console.log(res);
},
err => {
console.log(err);
}
)
newbie to React looking for some help... I'm using React to make API requests like so:
class CatsApi {
static createCat(cat) {
const request = new Request('http://localhost:4300/api/v1/cats', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(cat)
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
Meanwhile, I have authentication to my API via react-devise:
https://github.com/timscott/react-devise
Which has a method getBearerToken like so: https://github.com/timscott/react-devise/blob/master/src/actions/authTokenStore.js
How do I use getBearerToken to pass the API the token so API requests are authenticated with the token?
Thank you!
You can use the Authorization header like:
{ 'Authorization': `Bearer ${authToken}` }
Using fetch you could try with something like:
fetch('http://localhost:4300/api/v1/cats', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`
'Accept' : 'application/json',
'Content-Type' : 'application/json',
},
body: JSON.stringify({
cat : cat_value,
})
})
.then((response) => response.json())
.then((responseData) => { console.log(responseData) })
.catch((error) => { console.log(error) })
.done()
Also, it'd be great to see what's the Rails output in the console when you make a request, or the browser console.
I am using Angular2 in my application, And I saw advantages of using Observable while calling http calls. But somehow I am not able to make call when I am using Observable for POST requests, But it's working while GET request. If I use subscribe method, then POST is working.
Below is my code,
using Observable,
AddBreakoutsManually(breakoutUploads: Uploads): Observable<boolean> {
console.log("Data = ", JSON.stringify(breakoutUploads));
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post("/breakout/InsertUploads", JSON.stringify(breakoutUploads), options)
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
Using subscribe,
Adding(breakoutUploads: Uploads) {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http
.post('/breakout/InsertUploads', JSON.stringify(breakoutUploads), options)
.subscribe(data => {
alert('ok');
}, error => {
console.log(error.json());
});
}
My API,
[HttpPost]
public bool InsertUploads([FromBody]BreakoutUpload breakoutUploads)
{
return true;
}
What mistake I am making while using observable in POST call ?
Not sure what I changed, But it starts working with below code,
AddBreakoutsManually(breakoutUploads: Uploads): Observable<string> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(Configuration.Url_AddBreakoutsManually, JSON.stringify(breakoutUploads), options) // ...using post request
.map((res: Response) => res.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
I'm trying to send a POST request to the OneSignal REST API using fetch:
var obj = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'app_id': '(API KEY)',
'contents': {"en": "English Message"},
'app_ids': ["APP IDS"],
'data': {'foo': 'bar'}
})
}
fetch('https://onesignal.com/api/v1/notifications', obj)
I know you're not really supposed to put your API key in client code, but this is just a test to see if it would work. Besides, the error I'm getting isn't a bad response from the server, it's:
Possible Unhandled Promise Rejection (id: 0):
unsupported BodyInit type
I've tried putting a catch method on the fetch, but it doesn't get called.
At a bit of a loss, not really sure how to proceed.
Thanks in advance!
Even I tried the same POST request for One-Signal REST API for creating notifications,the below worked for me fine.
const bodyObj = {
app_id: "**********",
included_segments: ["All"],
data: {"foo": "bar"},
contents: {"en": "Hi good morning"}
}
fetch('https://onesignal.com/api/v1/notifications',{
method:'POST',
headers:{
'Authorization':'Basic **********',
'Content-Type':'application/json'
},
body:JSON.stringify(bodyObj)
})
.then((response) => response.json())
.then((responseJson) => {
console.log("success api call");
})
.catch((error) => {
console.error(error);
});
Have you tried to change your json to the one below?
JSON.stringify({
app_id: '(API KEY)',
contents: {en: "English Message"},
app_ids: ["APP IDS"],
data: {foo: 'bar'}
})
Or even tried a simpler json?
I'm struggling with this strange problem, I can't seem to solve. I'm using isomorphic fetch to to post data to a server. I'm sending the body as a JSON-string. But on the server, I can't read the body, it's just an empty object.
The stack is: node, react.
Here is the client-code:
handleSubmit = (event) => {
const { dispatch } = this.props;
fetch('/api/me', {
method: 'POST',
header: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'xxx'
})
})
.then(response => response.json())
.then( json => dispatch( login( json ) ))
.catch( err => console.log(err) )
}
The server code:
var jsonParser = bodyParser.json()
app.post( '/api/me', jsonParser, ( req, res ) => {
console.log('req', req.body);
})
I've tried googling the problem. But the few solutions I found, didn't to the trick.
All help is much appreciated.
BR
Martin
// UPDATE //
figured it out, it was a silly 's', I had forgotten. 'header' should be 'headers'
Thank you for the update that one of the params should be plural:
headers: {
'Accept': ...,
'Content-Type': ...
},
You appended it to the question. Please feel free to accept this as the answer, or to create a new answer with that text, and accept it. Then the "unanswered" queue will contain one less dangling entry for folks to stumble upon.