Having issues getting page title from html with meteor.http package - javascript

Meteor.http.call( 'GET', 'http://google.com', {}, function( error, response ) {
if ( error ) {
console.log( error );
} else {
console.log( response );
}
});
the problem is it keeps showing this error this is my first time using this package so am not sure if i really understand it.
this is the error on my console.
XMLHttpRequest cannot load http://google.com. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access.

HTTP Requests from the browser will always run into this CORS issue unless you specifically allow them with CORS headers.
Meteor has a good way of dealing with it. First up you do a call:
Meteor.call("httpRequest","http://myserver.com/path/to/file",params);
In the server you write a Meteor method like this
Meteor.methods({
httpRequest: function(url,params) {
// Send the http request here
})
});
You cannot do a call back to the client with the result of the http request, but you can put it into a database record, which the client subscribes to.

Related

FastAPI rejecting POST request from javascript code but not from a 3rd party request application (insomnia)

When I use insomnia to send a post request I get a 200 code and everything works just fine, but when I send a fetch request through javascript, I get a 405 'method not allowed error', even though I've allowed post requests from the server side.
(Server side code uses python).
Server side code
from pydantic import BaseModel
from typing import Optional
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["POST", "GET"],
allow_headers=["*"],
)
class data_format(BaseModel):
comment_id : int
username : str
comment_body : Optional[str] = None
#app.post('/post/submit_post')
async def sumbit_post(somename_3: data_format):
comment_id = somename_3.comment_id
username = somename_3.username
comment_body = somename_3.comment_body
# add_table_data(comment_id, username, comment_body) //Unrelated code
return {
'Response': 'Submission received',
'Data' : somename_3
}
JS code
var payload = {
"comment_id" : 4,
"username" : "user4",
"comment_body": "comment_4"
};
fetch("/post/submit_post",
{
method: "POST",
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json'
}
})
.then(function(res){ return res.json(); })
.then(function(data){ alert( JSON.stringify( data ) ) })
The error
What should I do to get around this error?
Thanks in advance.
To start with, your code seems to be working just fine. The only part that had to be changed during testing it (locally) was the URL in fetch from /post/submit_post to (for instance) http://127.0.0.1:8000/post/submit_post, but I am assuming you already changed that using the domain name pointing to your app.
The 405 Method Not Allowed status code is not related to CORS. If POST was not included in the allow_methods list, the response status code would be 400 Bad Request (you could try removing it from the list to test it). From the reference above:
The HyperText Transfer Protocol (HTTP) 405 Method Not Allowed response
status code indicates that the server knows the request method, but
the target resource doesn't support this method.
The server must generate an Allow header field in a 405 status code
response. The field must contain a list of methods that the target
resource currently supports.
Thus, the 405 status code indicates that the POST request has been received and recognised by the server, but the server has rejected that specific HTTP method for that particular endpoint. Therefore, I would suggest you make sure that the decorator of the endpoint in the version you are running is defined as #app.post, as well as there is no other endpoint with the same path using #app.get. Additionally, make sure there is no any unintentional redirect happening inside the endpoint, as that would be another possible cause of that response status code. For future reference, when redirecting from a POST to GET request, the response status code has to change to 303, as shown here. Also, you could try allowing all HTTP methods with the wildcard * (i.e., allow_methods=['*']) and see how that works (even though it shouldn't be related to that). Lastly, this could also be related to the configurations of the hosting service you are running the application; thus, might be good to have a look into that as well.
It's and old issue, described here. You need Access-Control-Request-Method: POST header in your request.

How to handle redirect request in react to download file on browser.

I am new to react & JS. Please help me out in solving below problem.
Scenario: I am getting a SEE_OTHER type of response from the backend which contains a URL of the file, I need to download that file on browser.
Response from the backend is something like :
{ status:"SEE_OTHER"
context: {
...
...
headers:
Access-Control-Allow-Methods: ["GET, POST, DELETE, PUT"]
Access-Control-Allow-Origin: ["*"]
Location:[url from where file is to be downloaded]
.....
}
}
I'm trying to download the file after extracting URL from the response and execute below function below:
async download(url) {
let res = await fetch(URL.format(url));
if(res.status >= 400) {
throw Error(`HTTP error: ${res.status}`);
}
if(res.status === 200) {
setTimeout(() => {
window.location.href = res.url;
}, 100);
}
}
But I'm getting below error on browser console.
Failed to load
'www.xyz.com/abc.json'
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:2000' is therefore not allowed
access. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
Above code works if I use this extension on chrome. But what is a permanent solution for this problem.
Also, is there any way I could download file directly from the response.
If you are using express use the following package in your backend service to solve the issue.
https://github.com/expressjs/cors
The issue is because browsers by default prevent cross origin/domain access for few security reasons. Please refer the following link,
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Axios API Twitter request not returning back user tweets

I am trying to call Twitters API and get a my tweets back so I can post them on a website I am creating.
When I run the following code I get an error.
XMLHttpRequest cannot load https://api.twitter.com/1.1/search/tweets.json?q=%SamSchaeferSays. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3333' is therefore not allowed access. The response had HTTP status code 400." And "bundle.js:30041 Uncaught (in promise) Error: Network Error.
I am new to API calls not using PHP - not sure what I am doing wrong here.
const tweet = 'https://api.twitter.com/1.1/search/tweets.json?q=%SamSchaeferSays';
function getUserTweet() {
return axios.get(`${tweet}`).then(function(response){
console.log(response.data)
console.log(response.status)
});
}
sample OAuth string
const DST = `OAuth oauth_consumer_key="${consumerKey}",
oauth_nonce="${}",
oauth_signature="${}",
oauth_signature_method="${}",
oauth_timestamp="${}",
oauth_token="${}",
oauth_version="1.0"
`;
A 400 Bad Request error means that the server doesn't understand your request. In your case there's a typo that prevents the request from going through (extra %). Try this:
const tweet = 'https://api.twitter.com/1.1/search/tweets.json?q=SamSchaeferSays';
function getUserTweet() {
return axios.get(`${tweet}`, { headers: { 'Authorization': 'YOUR_OAUTH_HEADER' } }).then(function(response){
console.log(response.data)
console.log(response.status)
});
}
This will fix the 400 Bad Request error, but you won't get any data back yet. The Twitter API requires you to authorize your request. Find out more in their documentation.
To allow applications to provide this information, Twitter’s API relies on the OAuth 1.0a protocol. At a very simplified level, Twitter’s implementation requires that requests needing authorization contain an additional HTTP Authorization header with enough information to answer the questions listed above. A version of the HTTP request shown above, modified to include this header, looks like this (normally the Authorization header would need to be on one line, but has been wrapped for legibility here):

How to get JSON with jQuery from another domain

I have a little page and I need to get JSON from another domain. If make this:
$.get( "http://dev.frevend.com/json/users.json", function( data ) {
console.log(data);
alert( "Load was performed." );
});
I get an error. I understand why it throws this error, but I don`t know how to aviod it. I have not acces to the server.
XMLHttpRequest cannot load http://dev.frevend.com/json/users.json. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access.
I also tried to use JSONP, but as I understand in that case server should wrap response with callback function, because I got a SyntaxError.
Is it possible to make this request with JSONP?
I tried
$.ajax({
url: "http://dev.frevend.com/json/users.json",
dataType: "jsonp",
jsonpCallback: "logResults"
});
function logResults(data) {
console.log(data);
}
But got
Uncaught SyntaxError: Unexpected token :
JSON is valid, I checked.
You need to allow access in your project configuration.
Below site has more information
http://enable-cors.org/server.html
Thanks,
Use JSONP in jquery for this purpose JSONP reference
Try to add a header into your PHP file which is responsible for executing every request.
header('Access-Control-Allow-Origin', '*');

Access-Control-Allow-Origin issue and angular $http service

Sorry for duplicating a question for this issue but I really tried to seek for a solution but I could not find it. So I use angular $http.get xhr request to retrieve data from the public api. I have next code
$http.get('http://www.carqueryapi.com/api/0.3/?callback=?&cmd=getMakes&year=2000&sold_in_us=1')
.success(function(d){ console.log(d); })
.error(function(d){ console.log( "nope" );
});
this returns in console:
XMLHttpRequest cannot load http://www.carqueryapi.com/api/0.3/?callback=?&cmd=getMakes&year=2009. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'blah-my-localhost-blah' is therefore not allowed access.
However if I user jquery getJson method it works just fine:
$.getJSON("http://www.carqueryapi.com/api/0.3/?callback=?", {cmd:"getMakes", year:"2009"},
function(data) {
console.log(data);
});
So obviously I can configure angular to send correct request since jQuery works fine?
Thank you for the response.
Use the $http.jsonp method to do a jsonp request along with JSON_CALLBACK as the callback name:
$http.jsonp('http://www.carqueryapi.com/api/0.3/?callback=JSON_CALLBACK&cmd=getMakes&year=2000&sold_in_us=1')
.success(function(d){ console.log(d); })
.error(function(d){ console.log( "nope" ); });

Categories

Resources