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.
Related
I have two servers, frontend (Next.js) and backend (express.js api server).
Frontend server is running without any additions. But I have an nginx proxy for backend.
So far everything is good because they are not connected yet.
Frontend: is working as it should be.
Backend: I can make calls directly from the backend itself (by self origin).
When I make a fetch get call from my frontend server to the backend server, it normally gives a cors error because the origins are different.
For this, I set the backend server with cors:
// /src/middlewares/cors.ts
import cors from 'cors';
const whitelist = new Set(['http://192.168.1.106:3000', 'https://192.168.148.132']);
// frontend: http://192.168.1.106:3000
// backend: https://192.168.148.132
const corsOptions = {
optionsSuccessStatus: 200,
origin: (origin: any, callback: any) => {
console.log('origin: ' + origin);
if (whitelist.has(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
// credentials: true,
};
export default cors(corsOptions);
and
// /app.ts
import cors from './middlewares/system/cors.js';
.
.
// setup cors
app.options('*', cors);
app.use(cors);
.
.
After doing this, I reach my main goal. The frontend server can make call to the backend server.
output:
But this time I notice a problem. I can't send self request to backend anymore (by self origin).
When dealing with this I looked at the origins that came to the /src/middlewares/cors.ts file that I showed above.
for frontend:
for backend:
I am using self signed ssl in nginx for back server.
And there is not any cors relevant headers in conf.
How can i solve this situation?
(If I'm missing something, you can point it out in the comments.)
The Origin header is only set in cross-origin requests. If you call your backend directly, the Javascript value is undefined, and in this case you must not restrict anything. You could, for example, write
if (!origin || whitelist.has(origin)) {
callback(null, true);
}
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
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
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
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