Accessing in Chrome POST response body from Cloudflare Worker - javascript

I am trying to read a response from a Cloudflare Worker API, I have not set anything sepcial about it and in Postman the request works as expected. I am guessing I am missing some header but I am not sure which one or even if that is the reason reading the reponses body is not working in browser.
This is how I fetch the data:
const url = `${process.env.SOME_URL}/v1/method?token=${TOKEN}`
const headers = new Headers();
headers.append("Content-Type", "application/json;charset=UTF-8");
const requestOptions = {
method: 'POST',
redirect: 'follow',
mode: 'no-cors',
body: JSON.stringify(body),
headers
// referrerPolicy: 'no-referrer',
};
return fetch(url, requestOptions)
.then(async (response) => {
// no body to be parsed
return response.json()
} )
.then(result => console.log(result))
.catch(error => console.log('error', error));
Looking forward to your answers, thank you.

This behaviour is due to the no-cors config of the fetch-api.
For more details read about opaque requests here:
What limitations apply to opaque responses?

Related

fetch Microsoft bearer token not working from the browser

I am trying to implement that
https://learn.microsoft.com/en-us/graph/auth-v2-service?view=graph-rest-1.0
Its working from node and postman but not the browser
This was copied from postman
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
myHeaders.append("Cookie", "fpc=blabl; stsservicecookie=estsfd; x-ms-gateway-slice=estsfd");
var urlencoded = new URLSearchParams();
urlencoded.append("client_id", "bla-bla");
urlencoded.append("scope", "https://graph.microsoft.com/.default");
urlencoded.append("client_secret", "bla-bla");
urlencoded.append("grant_type", "client_credentials");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
fetch("https://login.microsoftonline.com/blabla/oauth2/v2.0/token", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Any ideas what i should include or omit in the fetch request?
The code above will not work in the browser. This code above needs to be executed on the server (you are using "client secret").
If you want browser-only (SPA) authorization, consider using PKCE authorization flow instead.
Other than that, the code looks okay, there is nothing wrong with it.

Post request to the firebase cloud functions gives error 500

I have a POST request to the Cloud Functions on Firebase. When I'm trying to make a request, I get a CORS policy error. Ok, I set mode: 'no-cors' and get Failed to load resource: the server responded with a status of 500 ().
Here is the code
let myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Accept", "application/json");
let raw = JSON.stringify({
"description": "Test item",
"email": "testemail#gmail.com"
});
let requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
mode: 'no-cors',
redirect: 'follow',
};
fetch("https://someURl.cloudfunctions.net/someRequest", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
The code is copied from Postman
Any ideas?
As confirmed by jaba, the issue was on server side. Also, same has been documented here.

CORS blocking fetch function on Nestjs(server) and Vuejs(client) on localhost

im try to learn to build my own RestAPI by using node and nest js.
everything works fine, tested on POSTMAN: it works.
but when i tried to fetch it from my frontend, it being blocked by CORS.
although i have enabled the cors setting on Nestjs.
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors();
await app.listen(3000);
}
bootstrap();
and calling it from VueJS:
postPackageToServer: function () {
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
type: "monthly",
price: 30,
startDate: "04-08-2020",
endDate: "06-08-2020",
});
var requestOptions = {
method: "POST",
headers: myHeaders,
body: raw,
redirect: "follow",
};
let postData = async() => {
let postingDating = await fetch("localhost:3000/vouchers", requestOptions)
.then((response) => response.text())
.then((result) => console.log(result))
.catch((error) => console.log("error", error));
}
},
may i know what i did wrong? and how to fix it.
if this issue has been answered by other question, i would love to learn from it.
thank you
I'm pretty sure that you're only missing the CORS headers in your fetch request headers. Try adding this header to your myHeaders.append() method:
myHeaders.append('Access-Control-Allow-Origin', '*')
It looks like your code is ok.
try to add http/https protocol on the client request
try to change cors option
var corsOptions = {
origin: 'http://example.com',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs)
choke on 204
}

How to read variable value sent over Http Post and Get on AWS API Gateway Lambda using Javascript(Node.js)?

I am getting undefined on both POST and Get when I am doing it as bellow:
var name = event.queryStringParameters.name;
Is this a configuration I am missing or what?
To get payload within the body, you can use this solution as well.
Let say, you want to get the email from the event body. It should be like the below example.
Sending request within the body
the header will be "Content-Type: application/json"
and then in your lambda function, you are going to get the email like in the below screenshot.
JSON.parse(event.body).email
When you send payload within the body, the fetch request will be as in below
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({"email":"foo#bar.com"});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("http://127.0.0.1:3000/contact", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
PS: Above example, for cases, sending post requests within the body.

Bad request response to fetch REST API

I have built an API and app that uses that API. When I POST method via Postman, it works fine, but when I try fetching it via app, I get a bad request 400 status response. What am I doing wrong?
Here is my JavaScript code:
const myForm = document.getElementById('loginForm');
myForm.addEventListener('submit', function(e) {
e.preventDefault();
const url = 'https://thawing-peak-69345.herokuapp.com/api/auth';
const myHeaders = new Headers();
myHeaders.append('Accept', 'application/json, text/html, */* ');
myHeaders.append('Content-Type', 'application/json, charset=utf-8')
const formData = {
email: this.email.value,
password: this.password.value
};
console.log(formData);
const fetchOptions = {
method: 'POST',
mode: 'no-cors',
cache: 'no-cache',
headers: myHeaders,
body: JSON.stringify(formData)
};
fetch(url, fetchOptions)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.log(err))
})
Request
Response
Headers request:
Headers response:
You said:
mode: 'no-cors',
This is a declaration that you are not doing anything that requires permission be granted with CORS. If you try to do anything that does need permission, it will be silently ignored.
myHeaders.append( 'Content-Type', 'application/json, charset=utf-8')
Setting the Content-Type header to a value not supported by the HTML form element's type attribute requires permission from CORS. application/json is not such a value.
Consequently, the request is sent as text/plain.
Since it isn't marked as being JSON, the server throws a 400 error.
You need to:
Remove mode: 'no-cors',
Make sure that the service you are making the request to will use CORS to grant you permission (or to use a service on the same origin as the request).

Categories

Resources