I want to create a simple AJAX request to my ruby controller, but can not reach current_user.
The JS request:
var myHeaders = new Headers();
myHeaders.append('X-CSRF-Token', "P7qiN53QfDGbHjCXdV8BzL8McxgT1lBkXE3WpjP7taydWrF7d+xkZi+b9fG9TC13IMy61jmGK8pzhmdAoHjlZA==");
var myInit = { method: 'GET',
headers: myHeaders,
};
fetch('/get_user_last_activities.json', myInit).then(function(response) {
if(response.ok) {
console.log(response);
}
throw new Error('Network response was not ok.');
});
I use the 'omniauth-twitter' and 'omniauth-facebook' gems.
The response tells that current_user is nil 🤔
How can I teach my controller to access current_user when rendering .json responses?
It looks like your browser isn't sending the cookie with the fetch request. Try initializing like this:
var myInit = {
method: 'GET',
headers: myHeaders,
credentials: 'same-origin'
};
Related
Hello I have tried to use the instagram api to get a connection token. I first tested it on postman and this is what I did:
I used this link to make a request post to the instagram api:
https://api.instagram.com/oauth/access_token?client_id=clientid&client_secret=clientsecret&grant_type=authorization_code&redirect_uri=https://mysite/&code=thecode
The api gives me an error: Missing required field client_id
But when I set the content type to x-www-form-urlencoded everything works fine on postman.
So I tried to do the same thing in javascript with the node module request. I tried to do the same thing as on postman with the module but it does not work... Here is my code:
request(`https://api.instagram.com/oauth/access_token?client_id=clientid&client_secret=clientsecret&grant_type=authorization_code&redirect_uri=https://mysite/&code=` + code, {
method: 'POST',
headers: {"Content-Type": "x-www-form-urlencoded"}
}, (error, response, body) => {
console.log('body:', body)
})
As per MDN, the content type should be application/x-www-form-urlencoded
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
Update:
You should read the node doc : https://nodejs.dev/learn/making-http-requests-with-nodejs
Get method:
const https = require('https');
const options = {
hostname: 'api.instagram.com',
path: '/oauth/access_token?client_id=clientid&client_secret=clientsecret&grant_type=authorization_code&redirect_uri=https://mysite/&code=thecode',
method: 'GET',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "Accept-Encoding"
}
};
const req = https.request(options, (res) => {
// ...
});
Post method:
var headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "Accept-Encoding"
};
var options = {
url: 'https://api.instagram.com/oauth/access_token',
method: 'POST',
headers: headers
};
var form = {
grant_type:'urn:ietf:params:oauth:grant-type:jwt-bearer',
client_id: 'id',
client_secret: 'secret'
redirect_uri : 'https://mysite/&code=thecode'
};
var request = https.request(options, function(response) {
// do stuff
});
request.write(querystring.stringify(form));
request.end();
I am working on React web app with a Flask backend. how can I send a file with JSON data on the body?
I try the code below but is not working
const file = e.target.file[0]
const user = [{name: 'Ma'}]
const formData = new FormData()
dormData.append('file', file)
dormData.append('user', user)
const post = await axios({
method: 'post',
url: 'http://127.0.0.1:5000/route',
data: formData,
headers: { "Content-Type": "multipart/form-data" }
})
You have to set the Content-Type header as application/json and you can set the body as your json
Your code would look something like this
const post = await axios({
method: 'post',
url: 'http://127.0.0.1:5000/route',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(myJson) //insert your stringified json here
})
Since you are creting a react web app, it's easy to structure a JSON from a form.
You are spelling formData wrong. Use this code:
formData.append('file', file)
formData.append('user', user)
I use the following code using request which works as expected, got http response 200
var request = require('request');
var auth
var options = {
'method': 'POST',
'url': 'https://oauth2.k.de.com/oauth2/token',
'headers': {
'Accept': 'application/json',
'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'grant_type': 'client_credentials',
'scope': 'app:read'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
let body = JSON.parse(response.body);
….
Now I need to convert it to axios as request been deprecated but it’s not working for me ( I got http 400 response )
const axios = require('axios').default;
axios({
method: 'post',
'url': 'https://oauth2.k.de.com/oauth2/token',
data: {
'grant_type': 'client_credentials',
'scope': 'app:read'
},
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function (response: any) {
console.log("Head With Authentication :" + response);
}).catch(function (error: any) {
console.log("Post Error : " + error);
});
Any idea why with request library with the exact same data it works (http response 200) and in axios I got 400 ?
In request I put the grant_type etc in form and in axios in data, this is the only diffrencace I see, any idea?
This is the error I got
Request failed with status code 400
Should I use other rest libary if it cannot be done via axios ?
This is a bug, you might want to check this: https://github.com/axios/axios/issues/362
The problem is, because of axios interceptors, your Content-Type header is disappearing. If you have access and can change the backend, you can make it work with another header and set it on your client code. Otherwise if your code is working in a browser, you can try using URLSearchParams as suggested here.
I have a scipt tag in which im making a post request to a route through axios.Axios is not sending the parameters through.
Here is the code for axios:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
const data={'firstName':"sai"}
axios({
url: "/",
method: "post",
data: data,
})
.then(response => {
console.log(response);
})
.catch(error => console.error(error));
</script>
Here is the express side of things:
app.post("/",function(req,res){
console.log("post route");
console.log(req.body);
})
Im console.logging the data coming from the post request with the help of req.body(I also have body-parser working just fine.Tested with other normal forms).The req comes through to hit the post route.BUt the body is empty always logs "{}".
Please help me out with this.
Option 1:
Define config object
let config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}
Mandatory: Use array for params and not js object for 'application/x-www-form-urlencoded'
const params = new URLSearchParams();
params.append('PARAM1', 'VALUE1');
params.append('PARAM2', 'VALUE2');
Call post
axios.post( uri, params, config )
or
axios({
url,
headers: { 'content-type': 'application/x-www-form-urlencoded' }
data: params
})
Option 2:
Create an api instance (optional) and set default content-type
const api_local = axios.create({
baseURL: 'http://localhost:1000/myapi',
});
api_local.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Mandatory: Use array for params and not js object for 'application/x-www-form-urlencoded'
const params = new URLSearchParams();
params.append('PARAM1', 'VALUE1');
params.append('PARAM2', 'VALUE2');
Call post
api_local.post( uri, params )
I also have body-parser working just fine.Tested with other normal forms
Normal forms submit data encoded as either multipart/form-data or application/x-www-form-urlencoded.
Axios submits data, by default, as application/json.
You need a different body parser. One which supports JSON.
(Or to submit the data in a different format)
I am running nodeJS and have the following function:
const fetch = require("node-fetch");
async function createCustomer() {
let response = await fetch('https://sampleurl.com/login', {
method: 'POST',
body: 'username=usernameHere&password=passwordHere',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json, text/plain, */*'
}
});
tempVar = await response.json();
console.log(tempVar);
This logs in and authenticates, providing me a successful response.
However if I then try and do the next step, it fails with an unauthorized error.
let response2 = await fetch('https://sampleurl.com/list', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json, text/plain, */*'
}
});
tempVar2 = await response2.json();
console.log(tempVar2);
In python I use requests.Session() and do the initial authorization and then any API call after that just begins with 'session' and it works. For example::
session = requests.Session()
session.post('https://sampleurl.com/login',data={'username':'usernameHere','password':'passwordHere'})
response = session.get('https://sampleurl.com/list').json()
print(response)
This is the functionality I am trying to replicate, but I can't figure out how to store the session.
Any help would be much appreciated.
Edit: Using Express.
Edit2: This is not hitting an API I am running the server for, I am not looking for how to build this feature as the API server, rather just connect to an external API.