Vue.js Axios Post request blocked - spring-boot

I am trying to build a test app with a vue frontend and a spring boot backend. The backend receive a json from the frontend to register a new user.
But I am struggeling at the point to send a post request from the vue frontend to the backend. I only receive the status Blocked.
So this is the method in vue which should send the post request:
testMethodToClick() {
const data = {
"firstName": "Test",
"lastName": "Tester",
"email": "test.tester#test.de",
"password": "password"
}
const header = {
"Content-Type": "application/json",
"Accept": "*/*"
}
axios.post("http://ptsv2.com/t/ty0mk-1643012780/post");
axios.post("http://localhost:8886/api/v1/registration", data, header);
}
The first post request to ptsv2.com is just to test if the post request generally is working.
But this is the result:
But if I try to test the endpoint with postman, than it works:
So I did something wrong on the vue side.
Does someone know what I am missing?
Thank you very much!

Related

Axios JWT doesn't send

I have a project divided in two layers. The back-end is developed in spring boot, secured by Sprint security and JWT, and the front-end is developed in Vue.js, using Axios library for communication between layers.
I receive the "Bearer token" authentication properly, and all the authentication process is done correctly. The issue appears when I try to send a request with a token header to access content but the token doesn't send, and the Spring boot returns null without the content.
Here is the code
getOffers: function () {
if (localStorage.getItem("userSession")) {
this.aux = JSON.parse(localStorage.getItem("userSession"));
this.token = this.aux.token;
this.tokenHeader = "Bearer "+this.token;
alert(this.tokenHeader)
};
console.log(`Bearer ${this.token}`)
axios.
get('http://localhost:8080/api/v1/offer', {'Authorization' : `Bearer ${this.token}`})
.then(response => {
console.log(response);
this.offers = response.data
}).catch(e => console.log(e))
}
P.S: When I make a request in Postman, it works fine and returns the desired object. Here is a postman example:
postman
Correct way to pass header is :
axios.get(uri, { headers: { "header1": "value1", "header2": "value2" } })
In your case try this:
axios.get('http://localhost:8080/api/v1/offer', { headers:{Authorization : `Bearer ${this.token}`} })
Also, check in console if this gives correct Bearer token:
console.log(`Bearer ${this.token}`)
Register the Bearer Token as a common header with Axios so that all outgoing HTTP requests automatically have it attached.
window.axios = require('axios')
let bearer = window.localStorage['auth_token']
if (bearer) {`enter code here`
window.axios.defaults.headers.common['Authorization'] = 'Bearer ' + bearer
}
And no need to send bearer token on every request.

AWS Lambda API gives 502 error on POST request

POST request works fine for Lambda function and API. However, when I hit it through Postman then it gives 502 internal Gateway error.
When I print request in Clouwatch logs for Postman POST request, I get the following:
{
"resource": "/{proxy+}",
"path": "/entitlement",
"httpMethod": "POST",
"body": "ew0KICAgICJsYXN0UmVuZXdhbCI6IDE1MjcxNzY2Njg3OTUsDQogICAgInNvbGRUbyI6ICIwMDAxNjUyNDUzIiwNCiAgICAic3RhcnREYXRlIjogMTUyNzE3NjY2ODc5NSwNCiAgICAiZXhwaXJhdGlvbkRhdGUiOiAxNTI5NzY4NjY4Nzk1LA0KICAgICJhY3RpdmF0aW9uQ29kZSI6ICIxMTExMTExMTExMTExMTExIiwNCiAgICAicXVhbnRpdHkiOiAwLA0KICAgICJ2ZXJzaW9uIjogIjIxOSIsDQogICAgInRlcm0iOiAibW9udGhseSIsDQogICAgImFjdGl2ZSI6IHRydWUsDQogICAgIndlYmtleSI6ICJuZWhhLmNoaW5jaG9yZUBzaWVtZW5zLmNvbSIsDQogICAgInByb2R1Y3RTa3UiOiAiU0U5MTAtSVREIiwNCiAgICAiY3VzdG9tZXJJZCI6IG51bGwsDQogICAgImZpcnN0TmFtZSI6ICJUSElSRCIsDQogICAgImxhc3ROYW1lIjogIlRFU1QiLA0KICAgICJjb21wYW55TmFtZSI6ICJUaGlyZHRlc3QiLA0KICAgICJjYW5jZWxsYXRpb25EYXRlIjogbnVsbCwNCiAgICAiZW1haWwiOiAibmVoYS5jaGluY2hvcmVAc2llbWVucy5jb20iDQp9",
"isBase64Encoded": true
}
When I print request in logs for API Gateway, I get the following:
{
"resource": "/{proxy+}",
"path": "/entitlement",
"httpMethod": "POST",
"body": "{\"lastRenewal\":1532500221761,\"soldTo\":\"0001652453\",\"startDate\":1532500221761,\"expirationDate\":1535178621761,\"activationCode\":\"0449835557734402\",\"quantity\":0,\"version\":\"219\",\"term\":\"monthly\",\"active\":true,\"customerId\":null,\"firstName\":\"THIRD\",\"lastName\":\"TEST\",\"companyName\":\"Thirdtest\",\"cancellationDate\":null,\"email\":\"abc#xyz.com\"}",
"isBase64Encoded": false
}
GET request works fine. Face issue only for POST request.
In 'API-Gateway' console, expand API and select 'Settings' tab.
There is a field for 'Binary Media type', which was set to "*/*', due to which 'isBase64Encoded' is set to true in POST request.
However, my application was posting only json data in request body, so there is no need for 'binary support'. So we removed this field and it worked fine.
If you are posting binary data(images/files), in that case set 'Binary Media type' to respective file support type.

How to add Authorization header in vueJs

I'm trying to send a post request from a vuejs app to a spring backend with which I'm attaching a jwt authorization header.
I have tried with vue-resource
Vue.http.headers.common['Authorization'] = 'Bearer YXBpOnBhc3N3b3Jk';
and the backend headers are like this
{accept-language=en-US,en;q=0.5, origin=http://localhost:8080, host=127.0.0.1:8084, access-control-request-headers=authorization, connection=keep-alive,...
But if i use postman to send the same request, the backend headers are like this
{authorization=Bearer eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1OTBhYWFmMjRhNjQ3ZjRiYmZlMDBhMDQiLCJzdWIiOiJiYmIiLCJpYXQiOjE0OTM5NzUxMDQsInJvbGVzIjoidXNlciIsImV4cCI6MTQ5Mzk3NTQ2NH0.kldUh3H1i3xEiNcxQ2ecq1HsjIIF5BI8Q-tb3sALc3E, content-length=0, accept-language=en-US,en;q=0.8,.......
My question is, how can i achieve the postman header using vuejs. I have tried with axios as well but without success.
Try this way with axios. I'm using spring backend too and it works..
axios.post(
url,
query ,
{headers: {
"header name" : "header value"
}}
)
.then((response) => {
var response = response.data;
}, (error) => {
var error = error.response;
}
}
)

How to properly set Authorization to consume Wordpress Rest API (Oauth1) with Nativescript[2.5.4]?

I'm trying to consume the WP Rest API with Nativescript.
The WP API and the Authorization with OAUTH1 is already well setup and tested with POSTMAN.
Nativescript Login function to consume rest is already setup too and work without OAUTH.
Now I'm trying to Login with OAUTH here the code :
authorizationString = 'OAuth oauth_consumer_key="T2yXcbN28Ufj",
oauth_token="AmEVr5oSNmbKyZKccFjtmnSk",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1492267438",
oauth_nonce="rGFJG2",
oauth_version="1.0",
oauth_signature="Ru%2BaSvsZn2liesd2ENy8GeNsdHY%3D"';
login(user: User){
console.log("Try to login User : " + user.email);
let headers = new Headers({"Authorization": authorizationString});
let body = JSON.stringify({
username: user.username,
email: user.email,
password: user.password
});
headers.append("Content-Type", this.contentType);
return this.http.post(
this.api,
body,
{headers: headers}
)
.map( response => response.json() )
.do(data => {
//Do work!!
})
.catch(this.handleErrors);
}
But i got an error, this error means the autorization is not well formatted or sent :
"data": {
"code": "rest_cannot_access",
"message": "Only authenticated users can access the REST API.",
"data": {
"status": 401
}
}
How to properly use oauth1 with Nativescript?
I just switched to OAUTH2 by using a opensource plugin :
https://github.com/wlcdesigns/WP-OAuth2-Server-Client
and it's more easy to use with the authorization : Bearer

Post a message to slack using https://slack.com/api/chat.postMessage

I want to post a message to slack on x channel
I need to send the following x parameters
how do I send the following parameters to a website
"channel": "XXXXX",
"token": "token",
"text": "text"
Add your parameters to the end of Slack's chat.postMessage endpoint like this:
http://slack.com/api/chat.postMessage?token=XXX&channel=XXX&text=XXX
Then make a GET request to that URL to post your message. Personally I'd suggest doing this as a Node application and using the request package obtained via npm. Makes it very easy.
Post message to Slack in a Node App
Create a new node project and then change to that folder on the command line
On the command line type npm install -g request to install the request module for your project
Inside the index.js file (or wherever you plan on calling the API) do as follows:
//Import request module
var request = require('request');
//Replace your token, channelID and text here
var path_to_call = 'http://slack.com/api/chat.postMessage?token=XXX&channel=XXX&text=XXX';
request(path_to_call, function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log('Success');
} else {
console.log(error);
}
});
If you just want to post messages I would recommend to use an Incoming Webhook. They are specifically designed for that purpose and easier to use than API calls.
An Incoming webhook is a custom URL that you can create for your Slack team and then use to send messages into any channel. For sending a message you only need to submit your message in JSON format along with some parameters as POST request to your webhook URL.
If you are using PHP scripting on your website then you best use CURL for the call.
Check out the documentation for details on how to use it.
var url = "https://slack.com/api/chat.postMessage";
var auth_token = auth_token; //Your Bot's auth token
var headers = {
"Authorization": "Bearer " + auth_token,
"Content-Type" : "application/json"
}
var body = {
channel: userSlackId, // Slack user or channel, where you want to send the message
text: "Your text goes here."
}
request.post({
"url": url,
"headers": headers,
"body": JSON.stringify(body)
}, (err, response, body) => {
if (err) {
reject(err);
}
console.log("response: ", JSON.stringify(response));
console.log("body: ",body);
});
You have to set headers as Authorization, and add Bearer before your token as it is mentioned in slack docs. Also, send user/channel in body. Here I'm providing the link for the same for your reference https://api.slack.com/methods/chat.postMessage#channels . Hope this helps.
Not sure which language you're using, but if using Postman to test, you can try the following format.
raw Postman request
POST /api/chat.postMessage HTTP/1.1
Host: slack.com
Content-Type: application/json
Cache-Control: no-cache
{
"text": "This is a line of text.\nAnd this is another one.",
"token": "XXXX",
"channel": "XXXX",
}

Resources