GraphQL not making request to WP API - javascript

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

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;

Data posted to flask endpoint from JS not processed in endpoint

I have written a simple todo app with react acting as a frontend and flask handling CRUD from a DB. The app is using axios to handle the requests; GET completes fine however when attempting to POST JSON the flask api returns a 400 error. Here's some condensed sample code.
JS POST function.
function testPost(){
axios.post('http://'+window.location.hostname+':8000/todo/', {
title: "test123",
}).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
}
Serverside
class Todo(Resource):
def post(self): # create a new todo
conn = pool.getconn()
cur = conn.cursor()
app.logger.info(request.form['title'])
cur.execute("INSERT INTO todo (task, done) VALUES (%s, %s)", (request.form['title'], False))
conn.commit()
app.logger.error(e)
cur.close()
pool.putconn(conn)
Other methods not shown
Then the rest of the server code attaching the resource to the api and the CORS setup (not shown in file order)
app = Flask(__name__)
CORS(app, methods=['POST','GET','PUT','DELETE'])
api = Api(app)
api.add_resource(Todo, '/todo/')
app.run(debug = True, host='0.0.0.0', port=port)
Tests
Using python to test the api works fine, running this in a seperate python file will add to the DB.
response = requests.post(URL + "todo/", data={"title": f"test{randint(1, 100)}"})
My best guess is that axios is not adding the data to the request in a way that the backend is unable to process. Before using axios I tried to make the request with XMLHttprequest however this presented the same problem. I swapped to axios on the recommendation of someone else, given its alleged improved simplicity.
request.form['key'] and request.get_json()['key'] are completely different fields python requests in the way I used it posts to the former and js posts to the latter. Modifying the function to use whichever is available fixes this.

react fetch response meaning of type

While viewing the response using the fetch api in the react app created with create-react-app, the following output occurred.
I don't get the meaning of type in response. I mean, what type?
Since react dev port and strapi port is different, I set proxy configuration in package.json
"proxy": "http://localhost:1337"
Source code is just a simple fetch request for other port that I'm using with strapi.
useEffect(() => {
(async () => {
const result = await fetch(`${process.env.REACT_APP_API_HOST}/contents`, {
headers: {},
});
console.log(result);
})();
}, []);
What is the meaning of type in this response?
Thanks to #decpk Who commented on my post, finally knew what it means.
https://developer.mozilla.org/en-US/docs/Web/API/Response/type
It literally means the type of response, and
Since I used proxy option for request to cross-origin domain,
the response type meant 'cors' is Response was received from a valid cross-origin request.

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.

documentPath is not a valid resource path when deployed to Google App Engine with javascript

Description:
I have a frontend React client that is hosted on Firebase Hosting and a NodeJS Express API that is hosted on Google App Engine. The client needs to send a POST request to a NodeJS Express route, the request need to contain a variable called formid that holds the name of a firebase document. When both the server and client is run locally the formid variable gets sent to the API and it is not empty or undefined. But when the API is deployed and the request is sent to GAE instead I get this error:
UnhandledPromiseRejectionWarning: Error: Value for argument "documentPath" is not a valid resource path. Path must be a non-empty string.
The error appears in the Google Cloud Platform Console. In left hand menu I go to; Operations > Logging > Logs Viewer. But I can also tail the logs to my local console with the command "gcloud app logs tail -s default".
Question: Why does the error appear only when the request is sent to GAE and not when I run them locally?
request.headers.form_id contains the name of the document stored in a collection (which is an autoID) in Google Firestore.
async function postFormQuestionHandler(request, response) {
let form_ref = db.collection("forms").doc(request.headers.form_id);
... other code
Express router that recieves the request, forwards it to postFormQuestionHandler function.
router.post("/question", (req, res) => {
postFormQuestionHandler(req, res);
});
Here is where the request firstly is being sent:
async addQuestionsToFormDb(idToken, fomrid, questionids) {
let result = await questionids.map(async (questionid) => {
let data = {
idToken: idToken,
form_id: formid,
question_id: questionid,
};
return await fetch(`${process.env.REACT_APP_API}/form/question`, {
method: 'POST',
mode: 'cors',
headers: data
});
}
From above code I have also tried using the Axios library but it also produces the same error on when the API is deployed to GAE. I have tried reading the documentation of both Axios (Github Axios Documentation) and Fetch (Firefox MDN web docs) but it have not helped me, am I missunderstanding something? Below is what I tried with Axios:
return await axios.post(`${process.env.REACT_APP_API}/form/question`, {}, {
headers: data,
}
);
Other information
Im using Express v4.17.1 and Node v10.19.0, I am also developing this with WSL 2 on Windows 10 2004.
your request.headers.form_id is either empty string or contain invalid character. I guess it contains slash /. Here is more info https://firebase.google.com/docs/firestore/quotas#collections_documents_and_fields

Categories

Resources