POST request working on Postman but not using jquery POST - api

I am writing a dotnet core web api
the POST method on controller looks like :
// POST: api/SurveyUserResponses
[HttpPost]
public async Task<IActionResult> PostSurveyUserResponse([FromBody] List<SurveyUserResponse> surveyUserResponse)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.SurveyUserResponse.AddRange(surveyUserResponse);
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (SurveyUserResponseExists(surveyUserResponse[0].UserId))
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return new StatusCodeResult(StatusCodes.Status201Created);
}
This works fine 201 created when I use Postman to send this json :
[
{
"userId": 1,
"qId": 1,
"optionId": 0,
"response": "Suryansh",
"surveyCreatorOptions": null,
"user": null
},
{
"userId": 1,
"qId": 2,
"optionId": 0,
"response": "suryansh",
"surveyCreatorOptions": null,
"user": null
}
]
But when I use $.post("https://localhost:44366/api/surveyuserresponses/postsurveyuserresponse",JSON.stringify(jsonArr)); Chrome console shows 400(Bad Request)
For figuring out the problem I even tried copying the form data and sent it through Postman it works just fine.
I can't figure out the issue.

But when I use $.post("https://localhost:44366/api/surveyuserresponse/postsurveyuserresponse",JSON.stringify(jsonArr));
Since your server expects a payload of JSON, you need specify a header of Content-Type for the request:
$.ajax({
type: "POST",
url: "https://localhost:44366/api/surveyuserresponses/postsurveyuserresponse",
contentType: "application/json",,
data: JSON.stringify(jsonArr),
success: function(result){ /*...*/ }
});

Related

How to get response and show from backend in vue js

I have the following code:
data: function () {
return {
searchResults: []
}
methods: {
show() {
return axios({
method: 'get',
url: this.url,
headers: {
'Authorization': `Bearer ${localStorage.getItem('user-token')}`
}
})
.then (function (response){
return response.data['searchResults'];
})
.catch(e => { console.log(e) })
},
}
I have an onClick button. When I click the button, the show function executed and it send get response to my spring boot. After that it retrieves some data as I see in console, but the data is not displayed in browser. How can I fix it? The data I get looks like this:
JSON:
0: Object { "Code": "4326", code_color: 2, "name": "SomeName", … }
1: Object { "Code": "4326", code_color: 2, "name": "SomeName", … }
2: Object { "Code": "4326", code_color: 2, "name": "SomeName", … }
You should assign the returned data from api call in the show method to searchResults in the components data, so instead of
return response.data['searchResult']
you can use
this.searchResults = response.data.searchResult

Send additional info to server in uploading image process

im using filepond 4.25.1 on vue 2.6.11 and everything work without problem until now.
i want to send additional information to my server which is aspnet core 3. i send my request from filepond like below
myServer: {
url: "http://**********/api/CustomerAuth/",
process: {
url: "uploadimages",
method: "POST",
withCredentials: false,
headers: {},
data: {
nationalcode: "1234567890",
typecode:"1"
},
timeout: 7000,
},
load: (source, load) => {
fetch(source)
.then((res) => res.blob())
.then(load);
},
}
and server side
[HttpPost("uploadimages")]
public IActionResult UploadImages()
{
try
{
var file = Request.Form.Files[0];
string folderName = "Upload";
string webRootPath = _hostingEnvironment.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
if (file.Length > 0)
{
string fileName =
ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
string fullPath = Path.Combine(newPath, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
}
}
return Ok("Upload Successful");
}
catch (System.Exception ex)
{
return NotFound(new { img_upld_error = ex.Message });
}
}
in server side i need to access "nationalcode" and "typecode" which is send as data in process and value of these two parameters always change so its not static value and with interact of user value of this two always change.
I really appreciated if someone give me a some clue or guide me to solve my problem.
FilePond dev here.
data does not exist as a prop on process.
You can add additional FormData parameters with the ondata property. See updated example below:
myServer: {
url: "http://**********/api/CustomerAuth/",
process: {
url: "uploadimages",
method: "POST",
withCredentials: false,
headers: {},
data: {
nationalcode: "1234567890",
typecode:"1"
},
ondata: (formData) => {
formData.append('nationalcode', '1234567890');
formData.append('typecode', '1');
return formData;
}
timeout: 7000,
},
load: (source, load) => {
fetch(source)
.then((res) => res.blob())
.then(load);
},
}
Alternatively you can use the filepond metadata plugin to add metadata to each file (this is automatically sent to the server).
https://pqina.nl/filepond/docs/patterns/plugins/file-metadata/
FilePond.setOptions({
fileMetadataObject: {
'nationalcode': '1234567890',
'typecode': '1'
}
})
You can get file's in model, define your model like this
public class FileWithDataModel
{
public IFormFile File { get; set; }
public string NationalCode { get; set; }
public string TypeCode { get; set; }
}
and controller method will be :
public async Task<IActionResult> UploadFileWithData(FileWithDataModel model)
{
var file = model.File;
//you can save this file...
var nCode = model.NationalCode; //can access data easy
//......
return Ok();
}
Microsoft suggest to use Async method especially for file processing and uploading
here is example of jquery client
var form = new FormData();
form.append("NationalCode", "12345678");
form.append("TypeCode", "1");
form.append("File", fileInput.files[0], "/path/to/file");
var settings = {
"url": "http://**********/api/CustomerAuth/",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "application/x-www-form-urlencoded"
},
"processData": false,
"mimeType": "multipart/form-data",
"contentType": false,
"data": form
};
$.ajax(settings).done(function (response) {
console.log(response);
});

Fetch data in real time with flutter

I have an issue in my app that fetches data by getting it from another website. I want my screen to show the data in real time so if any changes happened on the website, it shows the changes in my app without the need to click on update or do any other action.
I tried to use future but I don't know how to use it. This is my code:
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
class FetchDataAPI {
get(String url, String function, Map<String, String> header) async {
List Response = List();
Response.clear();
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
// Internet connected
try {
var resBody = await http.get(
url,
headers: header,
);
print(resBody.statusCode);
// 200
if (resBody.statusCode == 200) {
Response = [json.decode(resBody.body)];
return Response ;
}
// Not 200
else {
Response = [
{
"exception": false,
"statusCode": resBody.statusCode,
// Body here depend on response post man
"body": json.decode(resBody.body),
"message": null
}
];
return Response;
}
} catch (e) {
Response = [
{
"exception": true,
"statusCode": null,
"body": null,
"message": e.toString()
}
];
return Response;
}
} else {
// Internet not connected
Response = [
{
"exception": true,
"statusCode": null,
"body": null,
"message": "No internet conected."
}
];
return Response;
}
} on SocketException catch (e) {
Response = [
{
"exception": true,
"statusCode": null,
"body": null,
"message": "No internet conected."
}
];
return Response;
}
}
}
You should use Streams, alongside StreamBuilder

vue js axios, send a POST to elasticsearch

In Vue JS using Axios I'd like to make a POST request to an Elasticsearch instance. More precisely I'd like to store a search template (https://www.elastic.co/guide/en/elasticsearch/reference/current/search-template.html#pre-registered-templates)
POST _scripts/<templateid> {
"script": {
"lang": "mustache",
"source": {
"query": {
"match": {
"title": "{{query_string}}"
}
}
}
} }
It works with CURL but I'm getting an error 400 when I'm trying with Axios.
My code is the following (with test as templateid)
var dataBody = {
"script": {
"lang": "mustache",
"source": {
"query": {
"match": {
"keyword": {
"query": "{{search_term}}"
}
}
}
}
}
};
this.$http.post(
"https://es-url/_scripts/test",
{
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
headers: {
Authorization: "Basic " + btoa("elastic:password")
},
params: {
source: dataBody,
source_content_type: 'application/json'
}
}
)
.then(response => {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Error:
Error: Request failed with status code 400
at createError (createError.js?2d83:16)
at settle (settle.js?467f:17)
at XMLHttpRequest.handleLoad (xhr.js?b50d:61)
I'm using the same Axios parameters to retrieve data (from my search queries), it works just fine, the difference is I can use GET for my search queries while I need to use POST to store a search template.
Looks like you've got Axios and jQuery's $.ajax mixed up.
If you are actually using Axios, it would look like this
this.$http.post('https://es-url/_scripts/test', dataBody, {
auth: {
username: 'elastic',
password: 'password'
}
})
Note that for this to work, you would need Elasticsearch configured with http.cors.enabled=true. See https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-http.html

405 error with JIRA REST API using node js

I am trying to create an automated JIRA ticket using the REST API but I keep getting a 405 error.
I am using the examples here: https://developer.atlassian.com/server/jira/platform/jira-rest-api-examples/
Also, when I visit the post URL directly I do not get any errors so I doubt it is a server issue. Any ideas?
var Client = require('node-rest-client').Client;
client = new Client();
// Provide user credentials, which will be used to log in to Jira.
var loginArgs = {
data: {
"username": "user",
"password": "pass"
},
headers: {
"Content-Type": "application/json"
}
};
client.post("https://jira.mydomain.com/rest/auth/1/session", loginArgs, function(data, response) {
if (response.statusCode == 200) {
//console.log('succesfully logged in, session:', data.session);
var session = data.session;
// Get the session information and store it in a cookie in the header
var args = {
headers: {
// Set the cookie from the session information
cookie: session.name + '=' + session.value,
"Content-Type": "application/json"
},
data: {
// I copied this from the tutorial
"fields": {
"project": {
"key": "REQ"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Request"
}
}
}
};
// Make the request return the search results, passing the header information including the cookie.
client.post("https://jira.mydomain.com/rest/api/2/issue/createmeta", args, function(searchResult, response) {
console.log('status code:', response.statusCode);
console.log('search result:', searchResult);
});
} else {
throw "Login failed :(";
}
});
I am expecting the Jira ticket of type REQ to be created with the details I added in the fields section.
I believe you are using the incorrect REST API; what you're currently doing is doing a POST to Get create issue meta which requires a GET method, hence, you're getting a 405. If you want to create an issue, kindly use Create issue (POST /rest/api/2/issue) instead.