I'm trying to grab an authentication token using axios in a react app.
Here is the error I'm getting is:
"XMLHttpRequest cannot load https://api.mmitnetwork.com/Token. Response for preflight has invalid HTTP status code 400"
Here is my code.
var App = React.createClass({
getInitialState() {
return {
token: ''
}
},
componentDidMount() {
var _this = this;
axios.post('https://api.mmitnetwork.com/Token', {
grant_type: 'password',
username: 'jpdesigning',
password: 'Upahem2_88'
}).then((response) => {
console.log('Success!')
_this.setState({
token: response.data
})
}).catch((error) => {
console.log(error)
})
},
render() {
return (
<div className="App">
{this.state.token}
</div>
);
}
})
export default App;
Your server needs to allow cross-origin (CORS) clients to access your headers by setting the following header on your server's response and telling it which headers they are (here you are allowing two headers: Authorization & Permissions - i.e. including custom headers)
Access-Control-Expose-Headers: Authorization, Permissions
Headers that are accessible by default:
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma
Read here Access-Control-Expose-Headers
example from php server for full CORS access
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true ");
header("Access-Control-Allow-Methods: OPTIONS, GET, POST");
header("Access-Control-Expose-Headers: Authorization");
header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size,
X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");
you need to set withCredentials: true, header , this will send the cookie along with this request
Related
``I am new with API requests, I have to use an API with authentication but I have an error. I have tried to solve the cors but I have not found the solution. When I put mode no-cors I have error 401. The API is external, I haven't access to modify anything
fetch("https://xxxxxxx",{
method:"GET",
headers: {
'Content-type' : 'application/json',
'Access-Control-Allow-Origin': '*',
"X-AMC-Vendor-Key": "xxxxxxxxx"
}
})
.then(res => res.json())
.then(
(result) => {
console.log('rsult 1', result)
},
(error) => {
// handle error
console.log('error', error)
}
)
Server also needs to allow cors, or add allow cors to response object.
Access-Control-Allow-Origin : //set this field as the client domain or *
Access-Control-Allow-Origin : http://example.client.come // this will give example.client.com as a client to bypass cors by browser
or
Access-Control-Allow-Origin: * // this will allow any client server to access the api on server domain
Here is my code:
axios
.post(
'https://app.adhg.ashdg/m/api/business/get-business',
{
'gid': getgid,
},
{
headers: {
'Cookie': cookie,
'Content-Type': 'application/x-www-form-urlencoded',
},
},
)
.then(function (response) {
// handle success
alert(JSON.stringify(response.data));
})
.catch(function (error) {
// handle error
alert(error.message);
});
I am implementing Axios post request in my React Native application. I want to send formurlencoded parameters along with the header called cookie.
In cookie I am storing AWS token value to send. But I am not getting the response, it says cookie is not sent. The same URL with params working perfectly in Postman. How can I pass cookie in the header?
Try something like this Cookie: name=value.
Mozilla Web Docs
I am working on a MERN stack app and when ever I send a delete request to my server using fetch api I get a cors error.
"Access to fetch at 'http://localhost:5000/api/users/delete-user' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
I have tried every solution for the problem here but nothing seems to work for me.
Here is my code
import express from 'express';
import mongoose from 'mongoose'
import cors from 'cors';
import productRoutes from './api/product-api.js';
import orderRoutes from './api/order-api.js';
import eventRoutes from './api/event-api.js';
import tutorRoutes from './api/tutor-api.js';
import assignmentRoutes from './api/assignment-api.js';
import userRoutes from './api/user-api.js';
import accomodationRoutes from './api/accomodation-api.js';
const app = express();
const PORT = process.env.PORT || 5000
// Middleware goes here!!!!
app.use(express.json());
app.use(cors());
// Connecting to database
mongoose.connect('mongodb://localhost:27017/hitstore', (err)=>{
if(err){
console.log("Could not connect to db");
} else {
console.log("Connected to the db");
app.listen(PORT, () => console.log(`http://localhost:${PORT}`))
}
})
// Routes
app.get('/', (req,res)=>{
res.json({message: "Hit store api"})
})
// routes middleware
app.use('/api/products', productRoutes);
app.use('/api/orders', orderRoutes);
app.use('/api/events', eventRoutes);
app.use('/api/assignments', assignmentRoutes);
app.use('/api/tutors', tutorRoutes);
app.use('/api/users', userRoutes);
app.use('/api/accomodations', accomodationRoutes);
Here is the code for my frontend
fetch(`${backendUrl}/api/users/delete-user`, {
method: "DELETE",
headers: {"Content-Type": "application/json", "Authorization": localToken},
body: JSON.stringify(userID),
})
.then(res => res.json())
.then(result => {
console.log(result)
})
.catch((err) => {
console.log("Could not send request\nErr: " + err);
})
The default configuration (which you are using) of Express's CORS middleware allows the DELETE method:
{
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false,
"optionsSuccessStatus": 204
}
No problem there. However,
because you're explicitly attaching the Authorization header (the one and only so-called non-wildcard request-header name) to your request , and
because you're specifying application/json as the value of the Content-Type request header,
you need to also explicitly allow those headers:
const corsOptions = {
allowedHeaders: ['Content-Type', 'Authorization']
};
app.use(cors(corsOptions));
I have a Vue.js application that uses axios to send request to ApiGee Server.
This is the code i use to send request to APIgee.
const headers = {
'X-API-Key': 'randomKey123123'
}
return axios({
method: 'get',
url: url,
headers: headers
}).then(response => {
console.log(response)
})
from the ApiGee, I can see OPTIONS request being received first since I done the request from the client side browser.
I can also see the X-API-Key header key but the value is missing.
The error I'm getting from the browser console is
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
Below code helped me you can try this format:
created() {
// POST request using axios with set headers
const article = { title: "Vue POST Request Example" };
const headers = {
'X-API-Key': 'randomKey123123'
};
axios.post(url, article, { headers })
.then(response => console.log(response.data)
);
}
I am trying to set up a Vuejs fronted application (vue-cli webpack template) to sit on top of my Laravel API.
I am able to get a successful response from the API with vue-resource by providing the correct auth token, for example:
methods: {
getUser () {
this.$http.get('http://localhost:8000/api/user',
{
headers: {
'Authorization': 'Bearer eyJ0e.....etc',
'Accept': 'application/json'
}
}).then((response) => {
this.name = response.data.name
});
},
However, I am now trying to set up interceptors so that the user's auth token will automatically be added for each request.
Based on the vue-resource readme I am trying this in my main.js:
Vue.use(VueResource)
Vue.http.interceptors.push((request, next) => {
request.headers['Authorization'] = 'Bearer eyJ0e.....etc'
request.headers['Accept'] = 'application/json'
next()
})
And then back in my component I now just have:
this.$http.get('http://localhost:8000/api/user').then((response) => {
this.name = response.data.name
});
Problem:
When I specify the headers in the get itself, I get a successful response, but when I pass them through the interceptor I get back a 401 Unauthorized from the server. How can I fix this to respond successfully while using the interceptor?
Edit:
When I use dev-tools to view the outgoing requests I see the following behavior:
When making the request by supplying the headers to $http.get, I make a successful OPTIONS request and then a successful GET request with the Authentication header being supplied to the GET request.
However, when I remove the headers from the $http.get directly and move them to the interceptor, I only make a GET request and the GET does not contain the Authentication header, thus it comes back as a 401 Unauthorized.
It turns out my problem was the syntax for which I was setting the headers in the interceptor.
It should be like this:
Vue.use(VueResource)
Vue.http.interceptors.push((request, next) => {
request.headers.set('Authorization', 'Bearer eyJ0e.....etc')
request.headers.set('Accept', 'application/json')
next()
})
While I was doing this:
Vue.use(VueResource)
Vue.http.interceptors.push((request, next) => {
request.headers['Authorization'] = 'Bearer eyJ0e.....etc'
request.headers['Accept'] = 'application/json'
next()
})
Add this option:
Vue.http.options.credentials = true;
And use the interceptors for global way:
Vue.http.interceptors.push(function(request, next) {
request.headers['Authorization'] = 'Basic abc' //Base64
request.headers['Accept'] = 'application/json'
next()
});