So I have a funny little problem.
When calling my API from an AngularJS client with the following code, everything works fine, except that my API only recieves an empty object as data:
var req = {
method: 'Post',
url: config.API + request.toLowerCase() + '/',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: data
}
$http(req)
.then(function(response){
// handling response
})
Now, if I remove the headers: { 'Content-Type': 'application/x-www-form-urlencoded' } or changes it to headers: { 'Content-Type': 'application/json' } I get the this error:
The requested resource does not support http method 'OPTIONS'
My API controller looks like this:
[EnableCors("*", "*", "*")]
[HttpPost]
public string Post([FromBody]dynamic value)
{
// Do some stuff
Response response = new Response();
return JsonConvert.SerializeObject(response);
}
What I'm looking for is a way to prevent the tiresome "OPTIONS not supported" error, and still be able to send dynamic data to my controller
EDIT
Regarding the duplicate, I've already tried their approach, hence why I already are using [EnableCors] in my controller. But if I add this:
public static void Register(HttpConfiguration config)
{
config.EnableCors();
}
I get this error instead
Response to preflight request doesn't pass access control check: The
'Access-Control-Allow-Origin' header contains multiple values '*, *',
but only one is allowed. Origin 'http://localhost:82' is therefore not
allowed access
Related
I am trying to send some form data to a spring application using Fetch API in javascript.
I have this code to send the form data:
document.querySelector('#formPet').addEventListener('submit', event => {
event.preventDefault();
let email= document.querySelector("#email");
fetch('http://localhost:8080/petForm/'+email.value+'/pets', {
method: 'POST',
body: JSON.stringify({
help: "helpme:("
})
})
});
but i get a 415 status error "Unsupported Media Type". Even when i set specifically the header 'Content-Type' to 'application/json' it sends like 'text/plain'
fetch('http://localhost:8080/petForm/'+email.value+'/pets', {
method: 'POST',
header: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
help: "helpme:("
})
})
});
this is the response that i get from the server:
Here is the method that accept the request in Spring:
#PostMapping("petForm/{id}/pets")
public ResponseEntity<Pet> createPet(#PathVariable("id") String ownerId, #RequestBody Map<String, Object> data){
System.out.println(data);
return ResponseEntity.ok().build();
}
i don´t know why the request is send in 'text/plain' format, i try the Spring method in postman and work´s fine when i send the data in json format.
In your JavaScript code you need to use „headers“ instead of „header“. See the fetch API documentation: https://developer.mozilla.org/en-US/docs/Web/API/fetch
step 1 : add #CrossOrigin after #PostMapping(value = "petForm/{id}/pets")
like :
#PostMapping(value = "petForm/{id}/pets")
#CrossOrigin
public ResponseEntity<String> createPet(#PathVariable("id") String ownerId, #RequestBody Map<String, Object> data){
System.out.println(data);
return ResponseEntity.ok().build();
}
step 2 : add double quotes to help word
it is not json fromat :====> help: "helpme"
Correct :
it is not json fromat :====> "help": "helpme"
I have tried many different ways but to no avail
API Spec - https://developers.facebook.com/docs/graph-api/reference/page/videos/
Param - content_tags ( list ) --> is what required
Below is my form data that is being posted
const formData = {
file_url: postOptions.filepath,
title: postOptions.title,
description: postOptions.description,
content_tags: ['tags', 'hello', 'hi']
};
HTTP Request Options
const options = {
url: https://graph-video.facebook.com/v9.0/${pageId}/videos?access_token=${accessToken},
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
},
formData,
};
Error response returned.
{"error":
{
"message":"(#100) Param content_tags[0] must be a valid ID string (e.g., \"123\")",
"type":"OAuthException",
"code":100,
"fbtrace_id":"ANoCbTSnh4uL960SjyE6XBV"
}
}
As per documentation, seems it has to be not just any string but NUMBER string which are predefined IDs of the tag list<numeric string>
From documentation
Tags that describe the contents of the video. Use search endpoint with type=adinterest to get possible IDs.
Example:
~~~~
/search?type=adinterest&q=couscous
~~~~
Here's full path of the above example shown by facebook, how you can get some IDs:
https://graph.facebook.com/search?type=adinterest&q="home"&limit =10&access_token={{access_token}}
I have this array and need to pass all the variables inside the request url.
I've tried as result.variable1, result['variable1'], result[0], but nothing works.
How can access each variable inside the array and pass to url?
result.push({variable1: string1, variable2: string2});
request.post({
url: "mydomain.com/text="Hi"+result[variable1]+"\\n"+result[variable2]+"Hello!",
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
},
rejectUnauthorized: false,//add when working with https sites
requestCert: false,//add when working with https sites
agent: false,//add when working with https sites
form: {
myfield: "myfieldvalue"
}
}, function (response, err, body){
console.log('Body:',JSON.parse(body));
}.bind(this));
result.push({variable1: string1, variable2: string2});
This will result in the array becoming as
result = [{variable1: string1, variable2: string2}].
So if you want 'variable1', you need to access it as result[0].variable1.
I make a call to an ASP.Net Web API which returns 404 Not found. The controller is recognized but the action is not found.
I have tried using attribute routing and [HttpGet] for the action. I've also tried using standard API routing in the WebAPI config file. I've even tried combining the two.
//[HttpGet]
//[Route("api/User")]
protected IHttpActionResult GetEmployeeHierarchyList()
{
// ...
return Json(results);
}
config.Routes.MapHttpRoute(
name: "GetEmployeeHierarchyListTwo",
routeTemplate: "api/{controller}/{action}",
defaults: new { action = "GetEmployeeHierarchyList", }
);
return fetch("/api/User/" + api, {
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'credentials': 'include'
}
}).then(response => {
return response.json();
})
I expect the action to return a string to be handled by the fetch call.
Make your GetEmployeeHierarchyList() method int the controller public.
This should workfine:
[HttpGet]
[Route("api/User")]
public IHttpActionResult GetEmployeeHierarchyList()
{
// ...
return Json(results);
}
I have a simple fetch request like this:
fetch('/data', {method: 'POST', credentials: 'same-origin', body: {'name': 'alice'}}).then(function(response){
console.log('reply:');
console.log(response);
});
Basically it should send a POST request to the local address /data with some parameters in it (same thing as an HTML form does) and then return the reply it gets (the /data page simply prints out "this is a test response")
But when I look at the console.log(response); it looks like this:
Response { type: "basic", url: ".../data", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, bodyUsed: false }
The actual string returned by the page /data ("this is a test response") is nowhere to be found.
So how can I retrieve the actual returned string then?
To read the body of the response, you need to actually do that. See the details on MDN (here, here, and here), but in brief, if you want the body as text, then:
fetch(/*...*/)
.then(function(response) {
return response.text();
})
.then(function(responseText) {
// ...
});