NgRok not reading method - ngrok

node js, and ngRock, it seems that ng rock is not receiving the GET method every time i make a GET request the method deployed in ngrok is OPTIONS /category, instead of GET / category.
picture
and im not getting any response from the server
react fetch
try {
const response = await fetch(global.config.Node_API + 'categorias', {
method: 'GET'
});
if (!response.ok) {
throw new Error(`Error!, Fallo en la coneccion`);
}
const result = await response.json();
this.setState({cont:1,categor: result});
} catch (err) {
console.log(err.message);
}
in the console im getting error
Access to fetch at 'https://5833-45-229-42-135.ngrok.io/categorias' from origin 'http://localhost:3001' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
in nodeJs im using
app.use(cors())

Related

Firebase: Cross-origin redirection to (url) denied by Cross-Origin Resource Sharing policy:Status code: 301 [duplicate]

This question already has answers here:
NextJs CORS issue
(10 answers)
Closed 8 months ago.
I am trying to deploy a firebase function and call the function from a nextjs app. The function works when it runs on firebase emulator, and when it is deployed I am able to call the function from postman. However, when deployed and I try to call using fetch I get an error. I have also tried to deploy the website to call from a different url but still get the same error.
Here is the calling function:
export async function getArticle(articleURL) {
const response = await fetch(articleURL);
const json = await response.json();
return json.result;
}
Here is the firebase function that I am trying to call:
const cors = require('cors')({origin: true});
exports.getArticle = functions
.runWith({
timeoutSeconds: 120,
memory: "1GB",
})
.https.onRequest(async (req, response) => {
cors(req, response, async() => {
try {
{code}
response.status(200).json({ result: 'test' });
}
catch (e) {
response.status(400).json({ result: "error", message: e.message });
}finally {
{code}
}
})
});
I have also tried adding headers such as:
response.set('Access-Control-Allow-Origin', "*");
response.set('Access-Control-Allow-Headers', "*");
but nothing seems to work. I have tried for hours but nothing works. The error I get is:
[Error] Cross-origin redirection to (url) denied by Cross-Origin Resource Sharing policy: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. Status code: 301
[Error] Fetch API cannot load (url) due to access control checks.
[Error] Failed to load resource: Cross-origin redirection to (url) denied by Cross-Origin Resource Sharing policy: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. Status code: 301
[Error] Unhandled Promise Rejection: TypeError: Load failed
Lastly, I have also tried adding parameters to my fetch call such as :
fetch(URL, {
mode: 'cors',
headers: {
'Access-Control-Allow-Origin':'*'
}
})
Overall, nothing seems to work and don't know what else to try. Any help would be greatly appreciated.
The problem was not with the firebase function but with the api call on nextjs. I was importing the function and making the call from a component. Instead I found the solution on this post: NextJs CORS issue.
The solution that worked for me was by chispitaos. I changed my getArticle function to the api format and fetched the internal api which then fetched the firebase function. Here was my new function:
export default async function handler(req, res) {
try {
const response = await fetch(`any url`);
const json = await response.json();
console.log(json);
res.status(200).send(json);
} catch (error) {
console.error(error)
return res.status(error.status || 500).end(error.message)
}
}
and here was how I called it :
const newData = await fetch('/api/getArticle');
This fixed the issue for me.

Ionic 6 Http Post shows unknown error in normalizedNames for capacitor project

I am calling my Wordpress REST JSON API in my Ionic Capacitor Project.
But i am getting the error shown in image below.
Ionic Capacitor HTTP Error
This is my code
const httpHeader = { // constant for http headers
headers : new HttpHeaders({
'Content-Type':'application/json',
'Access-Control-Allow-Origin': '*'
})
};
createComment(comment: Comment): Observable<any> {
return this.http.post('https://readymadecode.com/wp-json/wp/v2/comments/create,{
"post":4000,
"parent":"0",
"author_name":"chetan",
"author_email":"chetan#gmail.com",
"content":"nice good article"
},httpHeader).pipe(map(this.dataExtract),catchError(this.errorHandler));
}
private dataExtract(res: Response){ // This method extract data from the request response
const body = res;
return body || {};
}
private errorHandler(error: HttpErrorResponse){ // Method for error handler
console.error(error.error instanceof ErrorEvent?`Error message:
${error.error.message}`:`Error status: ${error.error.data.status} Body: ${error.error.message}`);
return throwError(`${error.error.message}`);
}
When i call the createComment function it shows error see in image above. I have tried enable CORS with cordova-plugins-whitelist but still it shows error.
But this api is working fine in postman. I am using this in postman.
URL: https://www.readymadecode.com/wp-json/wp/v2/comments/create
Method: POST
Body: {
"post":4000,
"parent":"0",
"author_name":"chetan",
"author_email":"chetan#gmail.com",
"content":"nice good article"
}
Please help how can i solve this error.
after try all the methods available on google, i able to solve this issue by simply removing the httpHeader from the api.
createComment(comment: Comment): Observable<any> {
return this.http.post('https://readymadecode.com/wp-json/wp/v2/comments/create,{
"post":4000,
"parent":"0",
"author_name":"chetan",
"author_email":"chetan#gmail.com",
"content":"nice good article"
},httpHeader).pipe(map(this.dataExtract),catchError(this.errorHandler));
}

how to send HTTP request with APIKEY

I have an API Gateway created to trigger my lambda function. I am trying to secure the invoke URL. I understand that we can use the Lambda Authorizer or the APIKEY. I am trying to use the API key but not sure how to pass the API key using fetch.
I have also linked the API to the API Keys and the usage Plans.
I am trying to access the URL from the client-side.
invokeurl is referring to my Invoke URL which will return the JSON object.
egkeyname is my key value which I am not able to share.
Client.py:
onMount(async () => {
const res = await fetch('invokeurl',{
method:'get',
headers: new Headers ({
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods':'OPTIONS,POST,GET',
'X-API-KEY' :'egkeyname'
})
}); //wait until the promise return result
data = await res.json();
});
But I get an error:
Access to fetch at '..invoke ur...' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
Uncaught (in promise) TypeError: Failed to fetch
GET https:invokeurl net::ERR_FAILED
My lambda function:
responseObject = {}
responseObject['statusCode'] = 200
responseObject['headers']={}
responseObject['headers']['Content-Type'] = 'application/json'
responseObject['headers']['Access-Control-Allow-Origin'] = '*'
responseObject['headers']['Access-Control-Allow-Methods'] = 'OPTIONS,POST,GET'
return responseObject
How do I access the URL with the APIkey?
Solved it on my own. I was using the wrong information in the Header.
It should be:
onMount(async () => {
const res = await fetch('invokeurl',{
method:'get',
headers: new Headers ({
'Access-Control-Request-Headers': 'Origin, X-Requested-With, Content-Type, Accept, Authorization',
'Origin' : '*',
'Access-Control-Request-Method':'OPTIONS,POST,GET',
'X-API-KEY' :'egkeyname'
})
}); //wait until the promise return result
data = await res.json();
});

event.passThroughOnException sends requests to origin, but without POST data

I thought that event.passThroughOnException(); should set the fail open strategy for my worker, so that if an exception is raised from my code, original requests are sent to my origin server, but it seems that it’s missing post data. I think that’s because the request body is a readable stream and once read it cannot be read again, but how to manage this scenario?
addEventListener('fetch', (event) => {
event.passThroughOnException();
event.respondWith(handleRequest(event));
});
async function handleRequest(event: FetchEvent): Promise<Response> {
const response = await fetch(event.request);
// do something here that potentially raises an Exception
// #ts-ignore
ohnoez(); // deliberate failure
return response;
}
As you can see in the below image, the origin server did not receive any body (foobar):
Unfortunately, this is a known limitation of passThroughOnException(). The Workers Runtime uses streaming for request and response bodies; it does not buffer the body. As a result, once the body is consumed, it is gone. So if you forward the request, and then throw an exception afterwards, the request body is not available to send again.
Did a workaround by cloning event.request, then add a try/catch in handleRequest. On catch(err), send the request to origin using fetch while passing the cloned request.
// Pass request to whatever it requested
async function passThrough(request: Request): Promise<Response> {
try {
let response = await fetch(request)
// Make the headers mutable by re-constructing the Response.
response = new Response(response.body, response)
return response
} catch (err) {
return ErrorResponse.NewError(err).respond()
}
}
// request handler
async function handleRequest(event: FetchEvent): Promise<Response> {
const request = event.request
const requestClone = event.request.clone()
let resp
try {
// handle request
resp = await handler.api(request)
} catch (err) {
// Pass through manually on exception (because event.passThroughOnException
// does not pass request body, so use that as a last resort)
resp = await passThrough(requestClone)
}
return resp
}
addEventListener('fetch', (event) => {
// Still added passThroughOnException here
// in case the `passThrough` function throws exception
event.passThroughOnException()
event.respondWith(handleRequest(event))
})
Seems to work OK so far. Would love to know if there are other solutions as well.

app.post on parse heroku server is unauthorized

I am trying to post to my server from twilio, but I am getting a 403 error. Basically my parse-heroku serve is rejecting any request from twilio. I am working with TWIMLAPP and masked numbers. I am having trouble posting to a function in my index file when a text goes through. In my TWIMLAPP my message url is https://parseserver.herokuapp.com/parse/index/sms Any help is appreciated. These are the errors in twilio
var app = express();
app.use(require('body-parser').urlencoded());
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'https://www.twilio.com');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader("X-Parse-Master-Key", "xxxxxxx");
res.setHeader("X-Parse-Application-Id", "xxxxxx");
// Pass to next layer of middleware
next();
});
app.post('/sms', twilio.webhook({ validate: false }), function (req, res) {
console.log("use-sms")
from = req.body.From;
to = req.body.To;
body = req.body.Body;
gatherOutgoingNumber(from, to)
.then(function (outgoingPhoneNumber) {
var twiml = new twilio.TwimlResponse();
twiml.message(body, { to: outgoingPhoneNumber });
res.type('text/xml');
res.send(twiml.toString());
});
});

Resources