How to set POST request via axios on REST API?
Headers
I see that get uncorrect headers, but I don't understand, why?
Also, I often come across the fact that the documentation of the axios simply doesn't work.
Example get GET request, it works:
Dynamic host in axios
const configAxios = {
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'Access-Control-Allow-Origin': '*',
},
};
const data = JSON.stringify({
cardData: this.cardData.brand,
});
axios.post('api/products', {
data,
},
configAxios,
)
.then((req) => {
this.data = req.data;
console.log(req);
})
.catch((err) => {
console.warn('error during http call', err);
});
This is necessary to get the host API:
p.s.: this will be work only in this way.
const baseURL = 'http://localhost:8080';
if (typeof baseURL !== 'undefined') {
Vue.axios.defaults.baseURL = baseURL;
}
axios version: e.g.: v0.16.2
Environment: e.g.: node v8.9.4, chrome 64.0.3282.119, Ubuntu 16.04
Symfony 4.0.4
Vue.js 2.4.2
vue-axios 2.0.2
If the API and the client are on separate domain names, you need to properly configure CORS headers to allow the client contacting the server. You also need to whitelist the authorized headers.
With API Platform and Symfony, you can easily do it using NelmioCorsBundle. If you use Symfony 4/Flex, run:
$ composer req cors
The package will be automatically installed and properly configured. `Content-Type] will even be whitelisted.
Related
The Firebase Documentation has some useful curl operations but doesn't provide information regarding Cors, headers, and auth using JS Fetch. We are using a fetch-only solution as I am creating a client-based Firebase npm package where users might not have the firebase modules imported for several reasons, tree shaking, minified project, etc.
I imagine I need to pass on the Auth as a header, What about Cors and credentials?
Here is a crude example, is this sufficient? or are there other unforeseen issues?
const pushOptions = {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}
var dataAPI = await fetch(databaseUrl+`/test.json`,pushOptions)
.then(response => response.json())
Reference:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
https://firebase.google.com/docs/reference/rest/database#section-put
The documentation says you need to pass your Firebase ID in query parameter 'access_token' and not in any header. For example,
curl 'https://[PROJECT_ID].firebaseio/users/jack/name.json?access_token=CREDENTIAL'
But I ended up getting Unauthorized errors.
However, the Authenticate with an ID Token section in Firebase Auth REST API documentation says, "pass the ID token generated above as the auth=<ID_TOKEN> query string parameter". A sample curl request for the same would be:
curl 'https://[PROJECT_ID].firebaseio/users/jack/name.json?auth=CREDENTIAL'
This request worked as expected.
About CORS, this answer says,
Firebase uses a fully-permissive cross-origin resource sharing (CORS) policy, meaning that you can make requests to the Firebase servers from any origin. This is possible because Firebase does not use cookies or traditional sessions to govern which requests are authorized and which are not.
Here's a working example using Javascript fetch:
firebase.auth().onAuthStateChanged(async (user) => {
const token = await firebase.auth().currentUser.getIdToken()
const pushOptions = {
method: 'GET',
}
const reqURL = "https://[PROJECT_ID].firebaseio.com" + `/path.json?auth=${token}`
const dataAPI = await fetch(reqURL, pushOptions)
.then(response => response.json())
.then(res => console.log(res))
})
I just used the client SDK to get an ID Token quickly but it will work irrespective of from where the token is generated - client SDK or Auth REST API.
The REST API accepts the same Firebase ID tokens used by the client SDKs.
I have a login page in my REACT website sending a POST request with fetch, but every time the request is submitted for some reason it refreshes the page and send it as a GET request, here's the method on my login page:
onSubmitSignIn = () => {
fetch("http://192.168.56.1:8560/signin", {
type: 'POST',
headers: {'Accept': 'application/json',
'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signinEmail,
password: this.state.signinPassword,
}),
})
.then(response => response.json())
.then(data => {
if (data ==='success'){
}
})
}
the server side signing page is as follows:
app.post('/signin', (req, res) => {
if (req.body.email === database.users[0].email && req.body.password === database.users[0].password){
res.json("success");
}else{
res.status(404).json("Error loggingin");
}
})
It's working fine with Postman, the server seems to be ok.
I have tried changing HTTP to https even though my server is HTTP just in case.
Tried restarting both servers, tried changing to fetch to axios but nothing seems to be working.
Any thoughts?
onSubmitSignIn = (event) => {
event.preventDefault() // <= You Need this
fetch("http://192.168.56.1:8560/signin", {
type: 'POST',
headers: {'Accept': 'application/json',
'Content-Type': 'application/json'},
body: JSON.stringify({
email: this.state.signinEmail,
password: this.state.signinPassword,
}),
})
.then(response => response.json())
.then(data => {
if (data ==='success'){
}
})
}
Create-React-App Proxying API Requests in Development -- src/setupProxy.js
People often serve the front-end React app from the same host and port as their backend implementation.
Such setup is not required. However, if you do have a setup like this, it is convenient to write requests like fetch('/api/todos') without worrying about redirecting them to another host or port during development.
To tell the development server to proxy any unknown requests to your API server in development, add a proxy field to your package.json, for example:
"proxy": "http://localhost:8560",
Configuring the Proxy Manually
First, install http-proxy-middleware using npm or Yarn:
$ npm install http-proxy-middleware --save
$ # or
$ yarn add http-proxy-middleware
Next, create src/setupProxy.js and place the following contents in it:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:8560',
changeOrigin: true,
})
);
};
API:
https://create-react-app.dev/docs/proxying-api-requests-in-development/
I'm just replying in case anybody has got the same issue as I was having, after a couple of sleepless nights digging through my code, I figure the template for my login page was taken from a "tachyon" template, what I missed, somewhere in my version control, was a "form" that was actually supposed to be turned into a "div", after going through this question here why-the-post-request-becomes-a-get-request it hit me, basically, if you happen to be taking the information from inside of a "form" and this form does not have a method post, it will automatically turn the API request into a GET request and fill up the URL with the information.
So that is sorted. Now let us tackle the rest of the bugs.
I am using vuejs / axios and I want to post data to a zapier webhook.
I've tried a number of things. However I continually get the following error:
Access to XMLHttpRequest at 'https://hooks.zapier.com/hooks/catch/7349379/owviy9/' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
Here is my code:
submit(){
axios
.post(
'https://hooks.zapier.com/hooks/catch/7349379/owviy9j/',
this.formData,
{headers: {"Accept": "application/json"}}
)
.then(function(response) {
console.log(response);
});
}
I've also tried this but can't seem to get it to work:
var data = this.formData
axios.create({ transformRequest: [(data, _headers) => JSON.stringify(data)] })
.post('https://hooks.zapier.com/hooks/catch/7349379/owviy9j/', data)
}
How do I resolve this CORS issue?
From your first example just remove:
{headers: {"Accept": "application/json"}}
Zapier dosn`t allow headers to be sent.
Complete example:
const res = await this.$axios.post('https://hooks.zapier.com/hooks/catch/xxx/xxx/',
JSON.stringify(data)
)
When you try to make requests from the same machine but with different ports. Example: Your front end is running on port 3000, while your nodejs app is running on port: 8080. For security concerns the browser doesn't let you make the api requests.
Solution: Add Cors to your NodeJs App.
npm install cors
const cors = require('cors')
const app = express();
just add a line below this: app.use(cors()); //use it as a middleware and this will resolve your issue.
Goal
Ensure security in my request message.
Environment:
Library: Version
node-fetch : 2.6.0
https : natively implemented in node, it seems
node : 12.15.0
Device : Version
Google home nest mini : 2nd generation
Issue
I get a "Failed to fetch" error when I do get request on an api served with https and self certified certificate.
What I tried:
1 - http request: it works fine on google home device and my local machine,
2 - https request: it works on my local machine but not on google home device.
Code I use:
import fetch from 'node-fetch';
import env from './configFile';
import https, { Agent } from 'https';
export default function get(): Promise<any> {
const url = "https://api.url";
const httpsAgent = new https.Agent({
rejectUnauthorized: false,
});
const option = {
method: 'get',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: 'Basic ' + btoa(env.login! + ':' + env.password!),
},
agent: httpsAgent,
};
return fetch(url, option)
.then(res => {
return res.json();
})
.catch(error => {
throw new Error(error);
});
}
Here I disable ssl certification verification. It is something i'll change later because it is not secure, but at least i want to do an https request without error.
My Errors
Go to this link: errors
Reproduce Error
I made a full tutorial, if you want to reproduce the error: https://github.com/killvi/localExecutionHttpsError
In this tuto, i try to make an https request on google to check if I can do it without error. So is not exactly same implementation as mine. But if it works with google, at least i will known that my problem does not come from https implementation in google home device.
Google answered my question:
Currently, local execution apps can only use unencrypted HTTP/TCP/UDP to communicate locally to their devices. It has been requested that we enable TLS capabilities over the local channel to enable HTTPS and other standard encrypted transport methods.
I am trying to send a file to the server using aurelia-fetch-client, but get the following error in the browser console. No 'Access-Control-Allow-Origin' header is present on the requested resource., but when I do the same with XMLHttpRequest file is uploaded.
Aurelia Fetch Client configuration and usage code
activate() {
await fetch;
this.http = this.httpClient();
this.http.configure(config => {
config
.useStandardConfiguration()
.withBaseUrl('http://localhost:3000')
});
}
makeRequest(data) {
this.http.fetch('upload', {
headers: {
'Content-Type': 'multipart/form-data'
},
method: 'post',
body: data
});
}
Following the comments here is the answer:
CORS was not enabled on the server, and Ilia suggested the use of the cors-express module if you are using node.
The following resources can be helpful for that:
http://enable-cors.org/server_expressjs.html
https://github.com/expressjs/cors