Request with GET/HEAD method cannot have body APOLLO-CLIENT - docker

I'm using docker network and try to use apollo-client, apollo-upload(createUploadLink) and I try to sent Barear token in headers too. the error show up Request with GET/HEAD method cannot have body
But if I change my url into real url [ not dockerNetwork everything work fine]
export const client = (req) => {
const uri = http://dockerNetwork:3000
return new ApolloClient({
link: authLink(req).concat(createUploadLink({
uri: uri ',
});),
cache: new InMemoryCache(),
});
};
const authLink = req => {
return setContext(_ => {
return {
headers: {
...req.headers,
authorization: `Bearer ${req.cookies.token)}`,
},
};
});
};
How can I fix this error by using docker network

Finally I found solution, first I use
"#apollo/client": "3.4.20"
"apollo-upload-client": "^16.0.0",
and I downgrade apollo/client to 3.3.20
"#apollo/client": "3.3.20",

Related

Unable to pass post variables in http request from Electron to Yii API

I want to make API (Get & Post) requests to an API build with Yii2 using Electron.
I have tried Axion, Fetch, HTTP, request modules and all of them gave me the same error:
data: {
name: 'PHP Notice',
message: 'Undefined index: username',
code: 8,
type: 'yii\base\ErrorException',
file: 'C:\xampp\htdocs\app\controllers\ApiController.php',
line: 898,
'stack-trace': [Array]
}
Here is the code for the action I want to call:
public function actionLogin(){
if(Yii::$app->request->isPost){
Yii::$app->response->format = Response::FORMAT_JSON;
$data = Yii::$app->request->post();
$username = $data['username'];
$password = $data['password'];
$device_token = $data['device_token'];
$prefix = substr($username, 0, 3);
$model = null;
}
}
And here is the code in Electron:
axios.post('http://localhost:8080/app/api/login', {
username: 'Fred',
psssword: 'Flintstone'
})
.then(function (response) {
console.log(response);
});
For some reason, the parameters are not passing to the action.
I have tried a lot of ways and this one seems to be the simplest.
P.S. all of the way I have tried gave the same error.
I have found the solution for this issue, the way it worked was:
const login = async(username, password)=>{
const data = new URLSearchParams();
data.append('username', username);
data.append('password', password);
data.append('device_token', 'null');
await fetch(`http://localhost:8080/app/api/login`,{
method: 'post',
body: data
})
.then(res => res.json())
.then(data => {
if(data.status){
ipcRenderer.send('user:login', data.data.user_type, data.data.access_token);
}
else{
document.querySelector('#message').innerText = 'Wrong password or username';
document.querySelector('#message').style.display = 'block';
}
})
}

"Only absolute URLs are supported" When fetch webhooks Nextjs

Im trying to fetch an webhooks url using Environment Variables.
here is my code
const url = process.env.WEBHOOK_URL;
const response = await fetch(
`${url}` ,
{
body: JSON.stringify({
name,
email,
message,
}),
headers: {
'Content-Type': 'application/json'
},
method: 'POST'
}
);
But the error show up "Only absolute URLs are supported"
please help! Thank you

How to get link to composition by using status callbacks twilio

Here is what I tried but it's not working.
This guy is responsible for creating a composition after the meeting is ended.
app.post('/api/endMeeting', (req, res) => {
const roomSid = req.body.roomSid;
userEmail = req.body.userEmail;
const client = require('twilio')(config.twilio.apiKey, config.twilio.apiSecret, {accountSid: config.twilio.accountSid});
client.video.rooms(roomSid).update({ status: 'completed' });
client.video.compositions.create({
roomSid: roomSid,
audioSources: '*',
videoLayout: {
grid : {
video_sources: ['*']
}
},
statusCallback: `${process.env.REACT_APP_BASE_URL}/api/getMeeting`,
statusCallbackMethod: 'POST',
format: 'mp4'
}).then(() => {
// sendRecordingEmail(composition.sid, userEmail);
res.status(200).send({
message: 'success'
});
}).catch(err => {
res.status(500).send({
message: err.message
});
});
});
And this guy will send the download link of the composition to the participant when it's available.
app.post('/api/getMeeting', (req, res) => {
if (req.query.StatusCallbackEvent === 'composition-available') {
const client = require('twilio')(config.twilio.apiKey, config.twilio.apiSecret, {accountSid: config.twilio.accountSid});
const compositionSid = req.query.CompositionSid;
const uri = "https://video.twilio.com/v1/Compositions/" + compositionSid + "/Media?Ttl=3600";
client.request({
method: "GET",
uri: uri,
}).then((response) => {
const requestUrl = request(response.data.redirect_to);
sendRecordingEmail(requestUrl, userEmail);
res.status(200).send("success");
}).catch((error) => {
res.status(500).send("Error fetching /Media resource " + error);
});
}
});
I can confirm that the composition is created exactly in the Twilio console.
But it seems the status callback guy is not working and I can see the below issue.
It seems I made mistakes in using the status callback.
Please let me know what is the problem and how I can solve this.
Thank you.
Thank you very much for #philnash's help in solving this problem.👍
I solved the above issue and I can get the download link of the composition for now.
The problem was in the status callback function and I should use req.body instead of req.query because of the status callback method. (It's POST on my code.)
Here is the code that is fixed.
app.post('/api/getMeeting', (req, res) => {
if (req.body.StatusCallbackEvent === 'composition-available') {
const client = require('twilio')(config.twilio.apiKey, config.twilio.apiSecret, {accountSid: config.twilio.accountSid});
const compositionSid = req.body.CompositionSid;
const uri = "https://video.twilio.com/v1/Compositions/" + compositionSid + "/Media?Ttl=3600";
client.request({
method: "GET",
uri: uri,
}).then((response) => {
const requestUrl = response.body.redirect_to; // Getting the redirect link that user can download composition
sendRecordingEmail(requestUrl, userEmail); // Send URL via email to the user
res.status(200).send("success");
}).catch((error) => {
res.status(500).send("Error fetching /Media resource " + error);
});
} else {
res.status(204).send('compositioin is not available');
}
});

MS Graph Sample Application Integration Test not Working

I want to do what the MS Graph sample node app is doing in its integrationTests.js, but that test doesn't work. Here's what I've tried:
Followed the quick start for creating a node.js app.
Ran the app. Ensured it worked by sending an e-mail.
Modified the test Checking that the sample can send an email to use my account parameters.
Tried to run the test. It fails with 403: insufficient scope. The call to get the token returned scopes, but lacked Mail.Send.
In the post data for the call to login.microsoftonline.com, I added "scope: 'Mail.Send'"
I still receive a valid token, and the return scope includes Mail.Send, but when I try to post with that token, I get 400: cannot POST /beta/me/sendMail
I tried adding scope (Mail.Send) in the query string and as a header (thought I saw that somewhere), but it made no difference.
I added the Mail.Send permission (under "Application Permissions") for the app in the application registration portal.
I compared the token (using https://jwt.ms) from my test call to the call from the app when it works. I see no real difference. They both contain the Mail.Send scope.
Here is the code (which is only slightly different from what's in the sample):
// in graphHelper.js
function postSendMail(accessToken, message, callback) {
request
.post('https://graph.microsoft.com/beta/me/sendMail')
//.post('https://graph.microsoft.com/beta/me/sendMail?scope=Mail.Send') // nope
.send(message)
.set('Authorization', 'Bearer ' + accessToken)
.set('Content-Type', 'application/json')
.set('Content-Length', message.length)
.set('scope', 'Mail.Send') // nope
.end((err, res) => {
callback(err, res);
});
}
describe('Integration', function () { // mocha
var accessToken;
var scope;
const config = getConfig();
// My account variables in testConfig.json file
function getConfig() {
var configFilePath = path.join(__dirname, 'testConfig.json');
return JSON.parse(fs.readFileSync(configFilePath, { encoding: 'utf8' }));
}
function getAccessToken(done) {
var postData = querystring.stringify(
{
grant_type: 'password',
//grant_type: 'client_id', // not supported
//grant_type: 'authorization_code', // This assumes you've requested an auth code.
resource: 'https://graph.microsoft.com/',
scope: 'Mail.Send',
client_id: config.test_client_id_v2,
client_secret: config.test_client_secret_v2,
username: config.test_username,
password: config.test_password
}
);
var postOptions = {
host: 'login.microsoftonline.com',
port: 443,
path: '/common/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
var postRequest = https.request(postOptions, function (res) {
var data = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
const response = JSON.parse(data);
accessToken = response.access_token;
scope = response.scope;
done();
});
});
postRequest.on('error', function (e) {
console.log('Error: ' + e.message);
done(e);
});
postRequest.write(postData);
postRequest.end();
}
before( // eslint-disable-line no-undef
function (done) {
getAccessToken(done);
}
);
it('Checking that the sample can send an email',
function (done) {
var postBody = emailer.generateMailBody(config.test_name, config.test_username);
graphHelper.postSendMail(
accessToken, scope,
JSON.stringify(postBody),
function (error) {
assert(error === null, `The sample failed to send an email: ${error}`);
done();
});
}
);
});

With a `new Request` in Node/React, how to pass params with a GET request?

I have the following API call in my Reactjs app:
static getAllSkills(title_id) {
const request = new Request(`http://localhost:4300/api/v1/job_title_skills`, {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify({title_id: title_id})
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}
Which points to a Rails endpoint which expects the param title_id like so:
def index
#skills = Skill.where(id: params[:title_id])
....
end
The controller is expecting a GET request however with the above, I'm getting the following JS console error:
Uncaught TypeError: Failed to construct 'Request': Request with GET/HEAD method cannot have body.
What is the right way to construct the Request and pass the param to the API?
I think the url in your api is waiting for the title_id maybe like:
api/v1/job_title_skills/:title_id
So you can append it in your url when you make the request:
static getAllSkills(title_id) {
const request = new Request(`http://localhost:4300/api/v1/job_title_skills/${title_id}`, {
headers: new Headers({
'Content-Type': 'application/json'
})
});
return fetch(request).then(response => {
return response.json();
}).catch(error => {
return error;
});
}

Resources