axios set custom cookies - javascript

Im trying to set a custom cookie, for axios requests. But it's not working.
Thats my code
const axios = require('axios');
axios.defaults.withCredentials = true;
const client = axios.create({
withCredentials: true
});
let url = 'https://google.de';
client
.get(url, {
headers: {
Cookie: [
'cookie1=value;'
],
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
}
})
.then(res => {
console.log(res.headers['set-cookie']); // Im getting "undefined"
})
.catch(err => console.error(err));
i tried different ways, but have no luck. maybee any one know how i can set custom cookies in axios? or recommend a better library to do that..

Related

CORS origin always undefined when fetching data

Using this server configuration
import Cors from 'cors';
const cors = Cors({
methods: ['GET', 'POST', 'HEAD'],
allowedHeaders: 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, X-Api-Authorize, X-Authorize',
credentials: true,
origin: (origin, callback) => {
console.log("*** TESTING", origin);
return callback(null, true); // debug, otherwise nothing works
},
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
});
const applyCors = async (req, res) => new Promise((resolve, reject) => {
cors(req, res, (result) => {
if (result instanceof Error) {
reject(result);
} else {
resolve(result);
}
});
});
export const apiMiddleware = handler => async (req, res) => {
await applyCors(req, res);
// ... req is extended with utils
return handler(req, res);
};
And a client fetch request like
const response = await fetch(`/api/data`, {
credentials: 'same-origin', // also tried "include"
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Api-Authorize': 'secret'
},
method: 'GET'
});
The server console.log always prints
*** TESTING undefined
When inspecting the request, I see the X-Api-Authorize header, but not Origin. What's missing?
fetch(`/api/data`
That's a relative URL, so you are making a same-origin request.
The origin header is only included in cross-origin requests.
(That's a simplification, as jub0bs points out, there are other times it will be included, but your code doesn't meet any of those conditions).

cors wont work even if Access-Control-Allow-Origin is set to *

I am working in a tiny project in react and express.js
the express.js code (Backend)
app.post('/api/search', (req, res) => {
//
res.setHeader("Access-Control-Allow-Origin", "*");
axios.get("[REDACTED]" + req.body.searchtxt + "&limit=100").then((response) => {
res.json({status: "ok", result: response.data})
})
})
and here the front-end
function SearchPage() {
const { searchText } = useParams()
const [SearchTxt, setSearchTxt] = useState(searchText)
useEffect(()=>{
fetch('http://localhost:8080/api/search', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
mode: 'cors',
body: JSON.stringify({searchtxt: searchText})
}).then((res) => {
res.json().then((resjson) => {
console.log(resjson)
})
})
},[])
}
but it shows this :
Access to fetch at 'http://localhost:8080/api/search' from origin 'http://localhost:3000'
has been blocked by CORS policy: Response to preflight request doesn't pass access control
check: 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've tried with Access-Control-Allow-Origin set to localhost:3000 but it don't work
Browser sends OPTIONS preflight requests by default when sending a request. So, you should send Access-Control-Allow-Origin header for that request as well.
The easiest solution is to use cors middleware package. You can use it like this:
const cors = require('cors');
app.post('/api/search', cors(), (req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*");
axios.get("[REDACTED]" + req.body.searchtxt + "&limit=100").then((response) => {
res.json({status: "ok", result: response.data})
})
})

React form pass headers to api

I want to post a JSON to a external api from a react form. the api needs headers (username:password) to access it. I wanted to see how I would set up a form to take the inputs of a user and pass it as headers to the api then post some json. I am able to do this with cURL but Im relatively new to react and this has been causing me some problems.
If you are using fetch to make API call you can do something like :
function signIn(username, password, body) {
const options = {
method: method,
headers: new Headers({username, password}),
mode: 'no-cors'
};
options.body = JSON.stringify(body);
fetch(url, options)
.then(response => response.json())
.then(data => console.log(data));
}
You might wanna read more about the same here
0
fetch(your_url,a_json_object) Here,json_object has one element called headers,just use your custom header in it. But most noobies forget to add the header in backend.I am showing a correct example:
front end:
fetch('fdf.api/getid',{
method:'post',
headers:{"a_custom_header":"custom_value"}
})
backend:
const express = require('express')
const app = express()
app.use(function(req,res,next){
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS,
PUT,PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,a_custom_header'); //notice here carefully
res.setHeader('Access-Control-Allow-Credentials', true);
next();
})

Why isn't my Fetch request sending custom headers in React-Native?

I am calling a fetch request akin to this.
fetch('https://api-endpoint.com/api',
{
method: "POST",
headers: new Headers({
'custom-header': 'custom header value'
})
}
)
.then(res=>{
/* code */
})
.catch(err=>{
/* code */
})
But it seems that the header is not being sent to the server. The server runs on Node.js, and I am attempting to reach it with React-Native.
I have allowed "access-control-allow-origin": "*" on the server, but to no avail.
I can also reach other endpoints on the server that don't require any headers.
And lastly, I have set the headers with both new Headers() and as an object.
What exactly am I missing to allow the headers to be sent? Is there a way to see exactly what is going on with my request in react-native?
It works in postman just fine.
EDIT:
I am using the cors middleware in my server.
app.use(cors())
appConfig.init(app);
Can you add these lines before using routes and try?
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization, custom-header"
);
res.header("Access-Control-Expose-Headers", "custom-header");
next();
});
And if you are using express cors middleware, you can add allowedHeaders and exposedHeaders options.
https://github.com/expressjs/cors#configuration-options
note if these configuration replaces the default headers, you may need to add the default headers to the options.
app.use(
cors({
exposedHeaders: ["custom-header"],
allowedHeaders: ["custom-header"]
})
);
Lastly you had better to use fetch api like this to send headers:
fetch('https://api-endpoint.com/api',
{
method: "POST",
headers: {
"custom-header": "custom header value"
}
}
)
.then(res => {
/* code */
})
.catch(err => {
/* code */
})
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Be sure,you added the header in:
res.header(
"Access-Control-Allow-Headers",
"Your_OWN_header,...."
);

Axios won't send cookie, Ajax (xhrFields) does just fine

Using Axios
export function sendAll() {
return (dispatch) => {
dispatch(requestData());
return axios({
method: 'POST',
url: `${C.API_SERVER.BASEURL}/notification/sendAll`,
data: {prop: 'val'},
// responseType: 'json',
headers: {
'Content-Type': 'application/json'
},
withCredentials: true
}).then((response) => {
dispatch(receiveData(response));
}).catch((response) => {
dispatch(receiveError(response));
// dispatch(pushState(null, '/error'));
})
}
};
Result using Axios
Using $.ajax
$.ajax({
url: " http://local.example.com:3001/api/notification/sendAll",
method: "post",
data: {},
crossDomain: true,
xhrFields: {
withCredentials: true
}
})
Result using $.ajax
I am unable to force Axios to send a POST when trying to attach data to POST (cookie doesnt get sent either way).
My server setup (express):
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", `${C.PROTOCOL}://${C.DOMAIN}:${C.PORT}`);
res.header("Access-Control-Request-Headers", "*");
res.header('Access-Control-Allow-Methods', 'GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
res.header("Access-Control-Allow-Credentials", "true");
next();
});
I do not have a OPTIONS route defined. I want Axios to send POST with cookie.
router.post('/notification/sendAll', function (req, res, next) {
res.sendStatus(204);
// ...
});
I was facing a similar issue. Making a get/post request through Axios did not sent the same headers as a straight XHR request.
Then I just added the following just after the Axios require statement:
axios.defaults.withCredentials = true;
After that Axios started sending my cookie like the regular XHR request did.
Working example using Danielo515's answer:
import * as axios from 'axios';
axios.defaults.withCredentials = true;
export function getAll() {
const url = 'https://example.com';
return axios.get(url);
}

Categories