How to send APIKey in Auth header in fetch request in Vue js - vue.js

I am trying to send post request to a url on which authorization of type API Key is enabled. I am able to send request through the post man. The API is responding perfectly fine, but when I come to fetch in Vuejs. I am unable to send the POST request using fetch.
Screenshot of POSTMAN is attached.
The tried code which I am using in Vuejs is:-
const requestOptions = {
method: "POST",
withCredentials: true,
headers: {
"Content-Type": "application/json",
"X-API-Key":"3C68F15FF89132BF254E5FB648FCA",
},
body: JSON.stringify({
name: this.name,
phonenumber: this.phoneNumber,
msg: this.message,
}),
};
let response = await fetch(
"https://auto.toxiclabs.net/webhook/d6121492-4b9c-4dc2-908f-991001b20b61",
requestOptions
);
The error I am getting
Anyone who can tell me what actually is wrong in my code ?

Related

How to handle the plain/text POST request in the cypress

I have a postman collection and It's POST call and the request body is type of plain/text and I just want to automate this using cy.request but I'm not sure how to pass the test body in the cy.request body section and it returned 400 bad request if I run the below code.
cy.request({
url: `${url}/user`,
method: "POST",
headers: {
'Content-Type': 'plain/text'
},
body: {
"confirmEmail": "true"
}
}).then(res =>{
cy.task('log',"Email id "+res.body.emailAddress);
return res.body;
});
}
The above request return .json response but the input request if text format and the same working fine in the postman tool.
Passing the request body in the below format in the postman tool and its working fine.
confirmEmail=true
My assumption is in the request body our endpoint is expecting a boolean value, but you are passing a string. So changing "confirmEmail": "true" to "confirmEmail": true should work.
cy.request({
url: `${url}/user`,
method: 'POST',
headers: {
'Content-Type': 'plain/text',
},
body: {
confirmEmail: true,
},
}).then((res) => {
cy.log(res.body.emailAddress) //prints email address from response body
})
In case you need to pass parameters in your URL you can directly use qs
cy.request({
url: `${url}/user`,
method: 'POST',
qs: {
confirmEmail: true,
},
headers: {
'Content-Type': 'plain/text',
},
}).then((res) => {
cy.log(res.body.emailAddress) //prints email address from response body
})

VueJs axios unauthorized POST request with Authorization header

I want to send POST with authorization to my REST api, but keep getting unauthorized. Everything works in postman, I have CORS enabled on the server.
axios
.post("/api/listings", {
headers: {
'Authorization': 'Bearer ' + this.token,
}
The header seems to appear to request payload in chrome debuggin tools.
I get the token from localStorage and it is definitely there.
My issue was that the header was being sent as an object in request body and not as a header.
Fixed the issue using this code:
axios
.request({
url: "api/listings",
method: "POST",
headers: {
Authorization: "Bearer " + this.token,
},
data:{
ListingName: this.name
}
})
.then((response) => {
console.log(response);
});
}

Cypress: Where does the authentication token go for an API request?

I am trying to request data through an API that requires authentification. I have the token and I know how to implement it using a manual tool such as postman...
How do I format the authentication using Cypress?
it('GET - read', () => {
cy.request({
method: 'GET',
url: 'https://mailtrap.io/api/v1/inboxes/123/messages?page=1&last_id=&useremail',
headers: {
Key: 'Api-Token',
Value: '1234'
}
})
})
})
Response:
The response we got was:
Status: 401 - Unauthorized
As per the Mailtrap documentation, sending an header Api-Token: {api_token} should send authenticated requests. You can write:
cy.request({
method: 'GET',
url: 'https://mailtrap.io/api/v1/inboxes/123/messages?page=1&last_id=&useremail',
headers: {
'Api-Token': 'Your Token value' //Replace with real token
},
failOnStatusCode: false
}).then((res) => {
expect(res.status).to.equal(200) //Replace with releveant 2xx response code
})

how to use axios to send data to line notify

I tried to send data to line notify server by axios and it fail
I have tried 2 version of code. as shown below
version 1 :
axios({
method: "post",
url: "https://notify-api.line.me/api/notify",
data: 'message="from vue"',
config: {
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "multipart/form-data"
}
},
Authorization: "Bearer [my token]"
})
.then(function(response) {
console.log(response);
})
.catch(function(response) {
console.log(response);
});
response is
XMLHttpRequest cannot load https://notify-api.line.me/api/notify due to access control checks.
Error: Network Error
and version 2 is :
axios
.post("https://notify-api.line.me/api/notify", "message=from vue", {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: "Bearer [my token]"
}
})
.then(response => {
console.log(response);
});
response is
Preflight response is not successful
XMLHttpRequest cannot load https://notify-api.line.me/api/notify due to access control checks.
Error: Network Error
What wrong with is
but I have tried in postman it work fine
Oh I am too familiar with this. Heres an explanation on stackoverflow as to why your request works with postman but not in browser. Long story short browsers send a preflight options check that will ask the server if the action you're about to perform is allowed. Postman does not. Usually the "Access-Control-Allow-Origin": "*" header is sent by the server to the browser not the other way around.
Inside the docs for LINE Notify you can find:
POST https://notify-api.line.me/api/notify
Sends notifications to users or groups that are related to an access token.
If this API receives a status code 401 when called, the access token will be deactivated on LINE Notify (disabled by the user in most cases). Connected services will also delete the connection information.
Requests use POST method with application/x-www-form-urlencoded (Identical to the default HTML form transfer type).
My guess is that your access_token might have been deactivated. Try requiring a new access token and doing the request again.
I think it is impossible to connect directly to the external url for the axios cuz ajax is basically for the inner data network. But you might have a controller if you do a web project, so you can just use your controller language to make a connection with line notify. In my case, I made a rails project and used axios in the vue.js, so I made a link like this.
View(axios) => Controller(Ruby) => LineAPI
me currently work on this too.
I did my app with node js.
My way below is for your reference, it works well.
const axios = require('axios');
const querystring = require('querystring');
axios({
method: 'post',
url: 'https://notify-api.line.me/api/notify',
headers: {
'Authorization': 'Bearer ' + 'YOUR_ACCESS_TOKEN',
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin': '*'
},
data: querystring.stringify({
message: 'something you would like to push',
})
})
.then( function(res) {
console.log(res.data);
})
.catch( function(err) {
console.error(err);
});
I try it works.
async function test() {
const result = await axios({
method: "post",
url: "https://notify-api.line.me/api/notify",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer [token]",
},
data: 'message=你好哇'
})
.then((response) => {
console.log(response);
})
.catch((err) => {
console.log(err);
});
}
test();
I think you can check response on chrome debugger network.
or provide more information, thx.

Upload a file but set Content-Type

I got Watson Speech-to-Text working on the web. I am now trying to do it on react native but am getting errors on the file upload part.
I am using the HTTPS Watson API. I need to set the Content-Type otherwise Watson returns a error response. However in react-native, for the file upload to work, we seem to need to set 'Content-Type' to 'multipart/form-data'. Is there anyway to upload a file in react-native while setting Content-Type to 'audio/aac'?
The error Watson API gives me if I set 'Content-Type': 'multipart/form-data' is:
{
type: "default",
status: 400,
ok: false,
statusText: undefined,
headers: Object,
url: "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?continuous=true",
_bodyInit: Blob,
_bodyBlob: Blob
}
The response body is:
{
"code_description": "Bad Request",
"code": 400,
"error": "No JSON object could be decoded"
}
Here is my code (full code is here - gist.github.com ):
const ext = 'aac';
const file_path = '/storage/emulated/0/Music/enter-the-book.aac';
data.append('file', {
uri: `file://${file_path}`,
name: `recording.${ext}`,
type: `audio/${ext}`
}, `recording.${ext}`);
const response = await fetch('https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?continuous=true', {
method: 'POST',
headers: {
// 'Content-Type': `audio/${ext}`,
'Content-Type': 'multipart/form-data',
'X-Watson-Authorization-Token': token
},
body: data
});
console.log('watson-stt::getResults - response:', response);
if (response.status !== 200) {
const error = await response.text();
throw new Error(`Got bad response "status" (${response.status}) from Watson Speach to Text server, error: "${error}"`);
}
Here is a screenshot of the error I get when I set 'Content-Type': 'audio/aac':
Thanks so much to DanielBolanos and NikolayShmyrev this is the solution I used:
This code is for iOS so I recorded the audio as blah.ulaw BUT the part_content_type is aduio/mulaw;rate=22050 this is very important to use mulaw even though file ext is ulaw. An interesting note: I couldn't play the blah.ulaw file on my macOS desktop.
Also note that you MUST NOT set Content-Type to multipart/form-data this will destroy the boundary.
Also Bluemix requires rate in the part_content_type for mulaw
const body = new FormData();
let metadata = {
part_content_type: 'audio/mulaw;rate=22050' // and notice "mulaw" here, "ulaw" DOES NOT work here
};
body.append('metadata', JSON.stringify(metadata));
body.append('upload', {
uri: `file://${file_path}`,
name: `recording.ulaw`, // notice the use of "ulaw" here
type: `audio/ulaw` // and here it is also "ulaw"
});
const response = await fetch('https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?continuous=true', {
method: 'POST',
headers: {
// 'Content-Type': 'multipart/form-data' // DO NOT SET THIS!! It destroys the boundary and messes up the request
'Authorization': `Basic ${btoa(`${USERNAME}:${PASSWORD}`)}`
},
body
});
According to the documentation for multipart requests the request should be:
curl -X POST -u "{username}":"{password}"
--header "Transfer-Encoding: chunked"
--form metadata="{
\"part_content_type\":\"audio/flac\",
\"timestamps\":true,
\"continuous\":true}"
--form upload="#audio-file1.flac"
"https://stream.watsonplatform.net/speech-to-text/api/v1/recognize"
So the content-type should be multipart/form-data, you can specify aac as "part_content_type": "audio/aac".
The big problem you have is that audio/aac is not in supported formats. You might probably need another codec.