POST functionality returns null value - vue.js

Post Functionality in Vue.js is returning a null value.
The API Call is local to my machine on a different port. The GET Functionality work as expected. The POST functionality doesn't work as expected only returns null.
fetch('http://localhost:8080/Exercise/lists/add', {
method: 'POST',
headers: {
"Content-Type" : "application/json",
},
body: JSON.stringify(this.user)
})
.then((response) => {
if(response.ok) {
console.log('Response is Ok.');
}
})
.catch((err) => {console.log(err)});
}
Expected to add a user. Rather returns a null value.
Console.log output here..
PostMan "post" service
PostMan "post" service working..

According to this site, the body of the post request is formated like 'foo=bar&lorem=ipsum'. But in your case the data are a JSON stringified object like "{"x":5,"y":6}". This could make a difference for your backend.
Also you can control the requests between your browser and the backend with the browser's network insepector (for Firefox it's Ctrl+Maj+J, then Network tab). It will tell you what data you send to your server and what is the response.

You should use Axios for API calls in Vue. You can find the Axios reference from the documentation https://v2.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html.
According to the documentation from Google when you use the POST request method you need to pass body and the image you uploaded shows you used firstName param. So either change your API and use body to get the first name or you can do something like this:
fetch('http://localhost:8080/Exercise/lists/add?firstName='+JSON.stringify(this.user), {
method: 'POST',
headers: {
"Content-Type" : "application/json",
},
body: ''
})
.then((response) => {
if(response.ok) {
console.log('Response is Ok.');
}
})
.catch((err) => {console.log(err)});
}

Related

Response to preflight request doesn't pass access control No 'Access-Control-Allow-Origin'

I have a Vue.js application that uses axios to send request to ApiGee Server.
This is the code i use to send request to APIgee.
const headers = {
'X-API-Key': 'randomKey123123'
}
return axios({
method: 'get',
url: url,
headers: headers
}).then(response => {
console.log(response)
})
from the ApiGee, I can see OPTIONS request being received first since I done the request from the client side browser.
I can also see the X-API-Key header key but the value is missing.
The error I'm getting from the browser console is
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
Below code helped me you can try this format:
created() {
// POST request using axios with set headers
const article = { title: "Vue POST Request Example" };
const headers = {
'X-API-Key': 'randomKey123123'
};
axios.post(url, article, { headers })
.then(response => console.log(response.data)
);
}

How to Fix '422 Unprocessable Entity' when sending a POST request to Redmine API?

I am trying to create a wiki page using redmine rest api.
The Authentication was succeeded, however the wiki page is not being created because of a 422 error.
The Redmine documentation says: "When trying to create or update an object with invalid or missing attribute parameters, you will get a 422 Unprocessable Entity response. That means that the object could not be created or updated."
But I can seem to find out where I have mess up. The PROBLEM CAME UP WHEN I DID THE SECOND REQUEST- "PUT REQUEST".
so we know the problem is somewhere in that section.
My guess is, it is either the file path or the content-type.
This is what I have so far....
const wordDocument="C:\Users\adasani\Desktop\practice\RedmineApi/RedmineText.txt";
creatingWikiPage_Request(wordDocument);
function creatingWikiPage_Request(wordDocument) {
axios({
method: 'post',
url: '<redmine_url>/uploads.json',
headers: { 'Content-Type': 'application/octet-stream' },
params: { 'key': '<api-key>' },
data: wordDocument
})
.then(function (response) {
console.log("succeeed---> ");
console.log(response.data.upload.token)
axios({
method: 'put',
url: '<redmine_url>/projects/Testing/wiki/WikiTesting.json',
headers: { 'Content-Type': 'application/octet-stream' },
params: { 'key': '<api-key>' },
data: {
"wiki_page": {
"text": "This is a wiki page with images, and other files.",
"uploads":[
{ "token": response.data.upload.token, "filename": "RedmineText.txt", "content-type": "text/plain" }
]
}
}
})
.then(response => {
console.log("PUT is Succeed-->>>")
console.log(response)
})
.catch(error => {
console.log("Error-->>")
console.log(error.response)
})
})
.catch(function (error) {
console.log("failed-----> ");
console.log(error.response.statusText, "-->", error.response.status);
console.log(error.response.headers)
console.log(error.message)
console.log("failed-----> ");
})
}
I am suppose to see a wiki page being created in my redmine dashboard but I am getting a 422 error.
You are sending the update request to the JSON api, i.e. <redmine_url>/projects/Testing/wiki/WikiTesting.json with Content-Type: application/octet-stream. Because of this, Redmine is unable to parse the PUTed payload since it doesn't know in what format the data is.
To solve this, you should always make sure to set the correct content type when posting data. In this case, you should set the Content-Type header to application/json when sending any JSON-formatted data to Redmine.
Note that in principal, you can send XML data to Redmine and get JSON back. The output format is determined by the file ending in the URL (.json or .xml), the format of the data sent by you is always identified by the Content-Type header.
I have similar issue while uploading multiple files to server from my flutter app; The issue is some server needs to have [] format to receive multiple files;
=> Change From
formData.files.add(MapEntry(
"videos",
await MultipartFile.fromFile(curPost.url, filename: getFileNameByFullPath(curPost.url)),
));
=> TO
formData.files.add(MapEntry(
"videos[]",
await MultipartFile.fromFile(curPost.url, filename: getFileNameByFullPath(curPost.url)),
));
Here I just make change key from videos to videos[].

How to force axios GET request to send headers?

Even though my code is inside one of my components in Vue, the problem is with Axios, let me explain why. So, I'm trying to get some information, like this:
axios.get('http://localhost:8181/roles/1',
{
headers: {
'Api-Token': 'tokenTOKEN',
'Content-Type': 'application/json'
}
}
)
.then(response => {console.log(response)})
.catch(response => {
console.log(response);
})
So, yes, I'm importing Axios correctly. Yes, I know we should not be sending a Content-Type header in a GET request. However, I already read the RFC 7231 and it doesn't say is impossible, is just not common. So, we want to send a Content-Type header in my request.
So, how do I know it doesn't work? Well, one of my middlewares in my Lumen API goes like this:
<?php
namespace App\Http\Middleware;
use Closure;
class JsonVerifier
{
public function handle($request, Closure $next)
{
if($request->isJson())
{
return $response = $next($request);
}
else
{
return response('Unauthorized.', 401);
}
}
}
I tried to use Postman to send that specific GET request, and it works. I tried to use fetch() like this:
var miInit = { method: 'GET',
headers: {
'Api-Token': 'tokenTOKEN',
'Content-Type': 'application/json'
},
mode: 'cors',
cache: 'default' };
fetch('http://localhost:8181/roles/1',miInit)
.then(function(response) {
console.log(response);
})
and it works! In both cases (with Postman and fetch()) my API returns the desire data.
However, when I try with Axios, I get a 401 response with the "Unauthorized" word, meaning that Axios didn't send the header correctly.
Now, the question. Is there any other way to send headers in an axios GET request? How can I force Axios to send the headers no matter what as it seem to be case with fetch() and Postman?
Axios automatically (as it should) removes the Content-Type header if you're sending a request without a body, as you do with any GET request.
https://github.com/axios/axios/blob/2ee3b482456cd2a09ccbd3a4b0c20f3d0c5a5644/lib/adapters/xhr.js#L112
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
// Remove Content-Type if data is undefined
delete requestHeaders[key];
} else {
// Otherwise add header to the request
request.setRequestHeader(key, val);
}
});
}
You're probably looking for the Accepts header and $request->wantsJson() (or acceptsJson()) instead.

Making POST to DRF using Axios

I'm trying to make a simple POST request using axios library inside of vuejs but for some reason, DRF is not receiving the parameters. When the same request is made via Postman it receives the parameters.
VueJS
postLogin(credentials){
return axios({
method: "POST",
url: "company/login/",
data: credentials,
}).catch(err => {
return TreatErrors.treatDefaultError(err);
})
}
DRF
#action(methods=['post'], detail=False)
# Debug set here shows POST comes empty from vuejs
def login(self, request, pk=None):
if not request.POST.get('email'):
raise ValidationError({
'message': 'You must provide an email'
})
Using the Chrome DevTools I can clearly see the parameters are being sent to DRF
What I have tried
I have tried coping every Headers from Postman and paste it in axios but without any luck
postLogin(credentials){
return axios({
method: "POST",
url: "company/login/",
data: credentials,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).catch(err => {
return TreatErrors.treatDefaultError(err);
})
}
Basically, I was accessing the data in the wrong way:
From this:
if not request.POST.get('email'):
raise ValidationError({
'message': 'You must provide an email'
})
To This
data = request.data
if not data.get('email'):
raise ValidationError({
'message': 'You must provide an email'
})

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.