Aftership Api with React fetch issue - javascript

I added aftership in my react app the following way:
const Aftership = require('aftership')('put-my-API-KEY', {
endpoint: 'https://api.aftership.com/v4'
});
let query = {
page:10,
limit:5
};
Aftership.call('GET', '/trackings', {
query: query
}, (err, result) => {
console.log(err);
console.log(result);
});
export default Aftership;
When I am using node src/aftership.js in terminal, then fetching data works well (after comment out last line export default Aftership).
But when I fetch from src/containers/Tracking.js file the following way:
import Aftership from '../../aftership';
...
componentDidMount (){
let query = {
page:10,
limit:5
};
Aftership.call('GET', '/trackings', {
query: query
}, (err, result) => {
console.log(err);
console.log(result);
});
}
it's showing me an error in console:
Failed to load https://api.aftership.com/v4/trackings?page=10&limit=5:
Request header field x-aftership-agent is not allowed by
Access-Control-Allow-Headers in preflight response. Tracking.js:28
TypeError: Failed to fetch Tracking.js:28 Undefined
Can anyone help me what is my issue and what should I do know?

This looks like a Cross-Origin Resource Sharing (CORS) problem. To simply put this is happening you are using your local development host with third party instead. To avoid such errors, you can use Chrome extensions like https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi. This extension will edit response header to Access-Control-Allow-Headers: '*', which allows all headers on request body.
This is not recommended for daily use, so I recommend to add wildcard for only APIs you would like to use. In this case add https://api.aftership.com/* to extension settings

Related

'Bad Request 400' response when getting outlook ics url

I've been running into issues on a legacy project that fetches ical feeds.
I am getting a response of "Bad request 400" when trying to get a calendar via any outlook.office365 url.
I have tested all the urls using PostMan and an online ics validator so I know that it has nothing to do with the calendars themselves not being available.
I am using the npm package 'request' to get the calendars and it's working with any url that doesn't come from the outlook.office365.com host.
For privacy reasons i'm not able to share any of the urls used.
Here is where the request is sent.
async.waterfall([
cb => {
request.get(url, {}, function (err, r, data) {
console.log('response', r.statusCode); // this will be 400 for any outlook.office365 ics url but not for others.
if (err) return cb(err, null);
try {
...
} catch (err) {
...
}
Are there any headers that need to be attached in order to receive outlook.office365 calendars? I can't find anything online about what is required
I had the same issue.
I compared the request headers in Postman and tried to mimic these in my application.
Adding the Postman User Agent string made it work for me:
HttpClient myHttpClient = new HttpClient();
myHttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
myHttpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("PostmanRuntime","7.30.1"));
var response = myHttpClient.GetAsync(calendarUrl).Result;

API does not allow origin when requesting from 127.0.0.1:8000

I'm currently developing a website on my localhost. A key component of the website must make requests to a third-party API (specifically https://api.commonstandardsproject.com/). The request is made via javascript running on the user's browser. However, when I attempt to run the following:
var reqUrl = 'https://api.commonstandardsproject.com/api/v1/jurisdictions';
axios.get(reqUrl, {
headers: {
'Api-Key': "vZKoJwFB1PTJnozKBSANADc3"
}
}).then((response) => {
var parsedResp = JSON.decode(response.data)
this.jurisdictions = parsedResp
}).catch((errors) => {
console.log(errors)
});
I receive a 401 from the API and an error stating that: error: "Unauthorized: Origin isn't an allowed origin.". Interestingly, I can access the API content fine (and without an API key) using just a browser or curl. When I check the origin of my request in the networks tab on chrome, it gives 127.0.0.1:8000. I believe this is the locus of the error, though I am uncertain of how to resolve it.
Can anyone tell me how to fix this? Thanks.
I've slightly modified your code to print the result to the browser console.
var reqUrl = "https://api.commonstandardsproject.com/api/v1/jurisdictions";
axios
.get(reqUrl, {
headers: {
"Api-Key": `MY API KEY`,
},
})
.then((response) => {
console.log(response);
})
.catch((errors) => {
console.log(errors);
});
I created an account and found I got the same results as you.
To get a successful response from the api I had to update my 'ALLOWED ORIGINS' in the sidebar of the https://commonstandardsproject.com/developers page to match the first part of the URL from the index.html file I was running in the browser.
E.g. the URL for the index.html I am running locally is:
http://10.0.1.159/index.html
I updated the ALLOWED ORIGINS to include the string
http://10.0.1.159
Allow Origins example
You will have to add the local address for the page you are testing from in the ALLOWED ORIGINS section of the developer page for the commonstandardsproject where you are signed into your account. Make sure to hit the 'update origins' button after you have entered the correct URL.

GraphQL not making request to WP API

Thanks in advance!
I'm pulling data from a WP Rest API and when spin up the wordpress site on my local machine with the address http://localhost:8000 and got to the graphqli playground on http://localhost:3000/api/graphql and i enter a query i get the expected results and i can consume the data happily in react but once i change the WP rest API address to http://example.com/cms i get back an error. The only thing that changes is the URL so i'm guessing it has to do with CORS.
Inspecting the browser window there is no CORS errors so i can rule out CORS being an issue. The strange thing is that when i make the api call via postman i get the response i expect, when i type in the endpoint in a browser i get the results i expect when i use the endpoint to resolve the query request i get an error, so i started to look at the headers as thats the only thing i can see that changes between a postman request and a normal browser request. for the local wp installation # localhost:8000 looking at the logs i can see the request being made from postman and the browser and axios(used in the query resolver) on the flipside the wp installation thats live on the web the logs show the request from postman and from the browser to the api endpoint but not from the graphql resolver. how do i fix this issue with the resolver not making the request?
this is my resolver for the query
const resolvers = {
Query: {
pages: (_parent, _args, _context) => {
return axios.get(`${wpURL}/wp-json/wp/v2/pages`)
.then(res => res.data)
.catch(error => {
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
});
}
}
}
graphqlserver:
import {ApolloServer} from 'apollo-server-micro'
import Cors from 'micro-cors'
import {schema} from './schema'
const cors = Cors()
const server = new ApolloServer({schema})
const handler = server.createHandler({path: '/api/graphql'})
export const config = {
api: {
bodyParser: false,
}
}
export default cors(handler)
terminal:
> next dev
ready - started server on http://localhost:3000
event - compiled successfully
event - build page: /api/graphql
wait - compiling...
event - build page: /api/graphql
event - compiled successfully
page:
What am i doing wrong?
i figured it out it looks like if the endpoint graphql is fetching data from is not secured via SSL it wont even bother asking for data

Why does failed dynamodb query fail with cors error on localhost instead of actual error?

In my development environment, I have a local copy of Dynamodb set up, using Reactjs to connect to it. I'm using the AWS SDK, in particular the query method for Dynamodb, to make queries.
When the query is properly structured, it runs fine. However, if the query is poorly structured, I get a cryptic response. The Chrome console gives me a:
POST http://localhost:8000/ 400 (Bad Request)
Access to XMLHttpRequest at 'http://localhost:8000/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
where localhost:8000 points to the local Dynamodb instance and localhost:3000 points to the react instance.
Most importantly, I don't get an error message dealing specifically with the mistake I've made. For instance, I might project a field with a reserved word, which then should correctly not work. However, I would expect an error saying "such and such word is reserved", not this CORS business.
Furthermore, when I run the same query from my node server, I do get a proper error message. This makes me wonder if the problem is related to reactjs somehow.
Is there any way to get a proper error message in my development environment as I've described? Thanks.
Edit:
As requested in the comments, here's a typical way I grab the data. Please note that this is a working query, so this is not generating an error. As I'm developing, though, this would be the type of query where I'd be making mistakes and not seeing good feedback.
// define tableName, indexName
async componentDidMount() {
// properties include an initiated docClient and organizationId
const [posts] = await Promise.all([ // typically I will fetch more than just posts (omitted for brevity)
new Promise((resolve, reject) =>
this.props.docClient.query(
{
TableName: tableName,
IndexName: indexName,
KeyConditionExpression: 'SortKey = :sortKey',
ExpressionAttributeValues: {
':sortKey': this.props.organizationId + delimiter + 'POST-Date'
},
ProjectionExpression: 'chatTitle, creatorName, creatorEmail, PostId, creationTime, #text, #data, lastModifiedTime, #status, mentions, attachments, chatType, creatorType',
ExpressionAttributeNames: { '#text': 'text', '#status': 'status', '#data': 'Data' }
},
(err, data) => {
if (err) {
reject(err);
return;
}
resolve(data.Items);
}
)
)
]);
// do something with posts, etc...
}
docClient is generated in a component using:
new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'})
where AWS is the aws-sdk module

Method PATCH is not allowed by Access-Control-Allow-Methods in preflight response

I am using axios PATCH method in ReactJS to update the record but its getting failed with following error
Failed to load http://192.168.99.100:8080/adslots/883: Method PATCH is not allowed by Access-Control-Allow-Methods in preflight response.
Here is my action:
export const UPDATE_AD_SLOTS_REQUEST = 'UPDATE_AD_SLOTS_REQUEST';
export const UPDATE_AD_SLOTS_SUCCESS = 'UPDATE_AD_SLOTS_SUCCESS';
export const UPDATE_AD_SLOTS_ERROR = 'UPDATE_AD_SLOTS_ERROR';
export function updateAdslotsRequest(){
return {
type: UPDATE_AD_SLOTS_REQUEST
}
}
export function updateAdslotsSuccess(data){
return {
type: UPDATE_AD_SLOTS_SUCCESS,
data: data
}
}
export function updateAdslotsError(errors){
return {
type: UPDATE_AD_SLOTS_ERROR,
erros: errors
}
}
export function updateAdslots(data, id) {
return dispatch => {
dispatch(updateAdslotsRequest());
return axios.patch(`http://192.168.99.100:8080/adslots/${id}`, data)
.then(res => {
dispatch(updateAdslotsSuccess(res.data));
})
.catch(errors => {
dispatch(updateAdslotsError(errors));
})
}
}
I am totally confused.
The api you are making the call to has to allow PATCH requests. They can do this by setting the Access-Control-Allow-Methods header to also have Patch in it. Look up how to do this with whatever server side language your api is using. You could also maybe try switching your call to a POST request but that is more of a temporary fix.
I think it is problem related to CORS settings on your backend. You have to allow PATCH requests in CORS settings. What kind of backend server are you using?
Try this solution:
Go to your app.js file where you've defined all the middleware.
Open terminal and type command "npm install cors", and hit enter.
Now write the following code in your file:
const cors = require("cors");
const app = express();
app.use(cors());
Hopefully, It will do the trick!
You can use any cors extension/plugin to make it work in browsers.
Also, make sure u have configured extension settings sometimes PATCH requests are not listed down in extension settings
Happy to help !
workaround : use browserplugin CORS (chrome)
when cors is activated you can open cors options and add localhost:3000 to the whitelist.
Then this thing is working for me

Categories

Resources