Error 415 when call POST API using Fetch in ReactJS - javascript

I want to call an API for register from method in React. Below is my javascript code :
fetch('http://localhost:5001/api/Account', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: "hugh.daniel#gmail.com",
name: "Hugh Daniel",
password: "1234"
})
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
And this is my controller
[HttpPost]
public ResponseModel RegisterByEmail([FromBody]UserModel user)
{
return _accountService.RegisterEmail(user);
}
But I always get these errors
I tried to add mode: 'no-cors' in my javascript code, but it makes Content-Type set to plain.
The API is working if I tested it using Postman like this

You need to combat CORS first of all. You can't make API requests against a different domain:port than the one from which it was served by development server. Are you using Webpack in your project? If yes, the easiest way is to set up API proxy by the Webpack configuration. See the doc. Something like this:
// webpack.config.js
devServer: {
port: 3030,
proxy: {
'/api': {
target: `http://localhost:5001`,
secure: false
}
}
}
Now you have to remove host:port from fetch address param and also I would add Accept header to the request settings:
fetch('/api/Account', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
// ...
}
)

try this
[ApiController]
[Consumes("application/json")]
[Produces("application/json")]
[Route("[controller]")]
public class TestController : ControllerBase
{}
In js:
await fetch(this.url, { method: 'POST', cache: 'no-cache', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) });
Sourse: https://pretagteam.com/question/angular-http-post-formdata-unsupported-media-type-from-c-controller

Do not use JSON.stringify in the body for sending a request and following code will do the work.
fetch('http://localhost:5001/api/Account', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: {
email: "hugh.daniel#gmail.com",
name: "Hugh Daniel",
password: "1234"
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

Related

How can I include authorization Headers in my react-app?

On postman, I can access endpoints by adding the headers:
Key: Value ( I will insert fake figures for example)
x-mash-auth-token: gdjsjaosh-hkds-dhjsk-hjjdbahsj
I am building a react app that allows user to search endpoints, how can I include this header in my code to grant user access on UI?
axios({
url: "API URL",
method: "GET",
data: {name: "abc"},
contentType: 'application/json',
headers: {
"Access-Control-Allow-Origin": "*",
'Accept': 'application/json',
'Content-Type': 'application/json',
'Pragma': 'no-cache',
'Authorization': 'Bearer gdjsjaosh-hkds-dhjsk-hjjdbahsj',
'Access-Control-Expose-Headers': "jwt_token"
},
responseType: 'json'
})
.then(function (response) {
successCallback(response);
})
.catch(function (error) {
errorCallback(error);
})

fetch-mock: No fallback response defined for POST

All my GET requests are going through but POST ones fail. This happens when I update fetch-mock from 7.3.0 to 7.3.1 or later.
console.warn Unmatched POST to url
Error fetch-mock: No fallback response defined for POST to url
http.js
export const get = (url) => {
const options = {
method: 'GET',
credentials: 'same-origin'
};
return fetch(url, options).then(handleJsonResponse);
};
export const post = (url, body) => {
const headers = {
'content-type': 'application/json',
'pragma': 'no-cache',
'cache-control': 'no-cache'
};
return fetch(url, {
credentials: 'same-origin',
method: 'POST',
cache: 'no-cache',
body: JSON.stringify(body),
headers
}).then(handleJsonResponse);
};
http.spec.js
const url = '/path/to/url'
describe('get', () => {
it('makes a GET request', async () => {
fetchMock.mock({
name: 'route',
matcher: url,
method: 'GET',
credentials: 'same-origin',
response: {
status: 200,
body: []
}
});
const response = await get(url);
expect(fetchMock.called()).toEqual(true);
expect(fetchMock.calls().length).toEqual(1);
expect(fetchMock.calls('route').length).toEqual(1);
expect(response).toEqual([]);
});
});
describe('post', () => {
const requestBody = {request: 'request'};
it('makes a POST request', async () => {
fetchMock.mock({
name: 'route',
matcher: url,
method: 'POST',
credentials: 'same-origin',
cache: 'no-cache',
body: JSON.stringify(requestBody),
headers: {
'content-type': 'application/json',
'pragma': 'no-cache',
'cache-control': 'no-cache'
},
response: {
status: 200,
body: []
}
});
const response = await post(url, requestBody);
expect(fetchMock.called()).toEqual(true);
expect(fetchMock.calls().length).toEqual(1);
expect(fetchMock.calls('route').length).toEqual(1);
expect(fetchMock.lastOptions().headers).toEqual({
'content-type': 'application/json',
'pragma': 'no-cache',
'cache-control': 'no-cache'
});
expect(response).toEqual([]);
});
});
Any thoughts on what's causing this? Is there a way to get more meaningful logs to help with debugging this?
I would rather not go the alternative path of trying nock or jest-fetch-mock.
Alright, after hours of digging into the library itself I have found out where the issue was.
In my code (and the snippet above) I am stringifying the body JSON.stringify(body). The library's generate-matcher.js is parsing it JSON.parse(body) and then compares the two - the point which was causing the failure. I am now just sending it as the raw object.
In case anyone else ends up here in the future, I had the same error accompanied with fetch-mock unmatched get.
I saw the response to this issue filed to fetch-mock which prompted me to double check my expected values and mocked values.
It turns out my problem was exactly as the error described, where the mock route I was expecting and the actual route that was being called were mismatched because of a typo.

Multiple headers in REST call giving #415 error

I have this REST request that I can't seem to get to work correctly.
This is just the "login" to the resource but I assume the same problem will occur as I move forward.
var bodyinfo = {
ApiKey: "#theapikey",
Username: "#theusername",
Password: "#thepassword" };
fetch('{base-url}/user/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
mode: 'no-cors',
body: JSON.stringify(bodyinfo)
})
.then(function(response){
return response.json();
})
.then(function(data){
console.log(data)
});
I've tried to stringify the headers as well but I always end up getting 'Status Code: 415 Unsupported Media Type'.
The HTTPRequest works fine when testing with either Postman or when I run it through a HTTPRequest in WebStorm.

ReactJS- Pass the JWT token as Authorization in axios method for http request

I have an application where we are generating a JWT token and passing that token in Header in the next api call.As a response of that, I should get a key.I am able to see the response through postman.I am using ReactJS in Front End and trying to achieve the same by passing the JWT token in Header while doing the api call but facing some issues.
My code-
getKey() {
let postData = {
vin: "5678",
id: "abc12",
};
axios({
method: "post",
url: "http://localhost:8080/generateKey",
headers: {
"Content-Type": "application/json"
},
data: postData
})
.then(function(response) {
setKey(response.data.key);
})
.catch(function(error) {
console.log(error);
getKeyError();
});
}
memberAuth() {
var self = this;
axios({
method: "GET",
url: "http://localhost:8080/authenticateMember",
headers: {
"Content-Type": "application/json",
"Authorization": localStorage.setItem()
},
data: {
"id":"xyzzy",
"password":"abc"
}
})
.then(function(response) {
//to do
}
I am trying to save the generated token (valid for 30mins) in a localStorage/SessionStorage but not sure if this is the right way. Can someone tell me where am I going wrong.
Create instance of your axios,
const agent = axios.create({
baseURL: config.api_url,
transformRequest: [transformRequest],
transformResponse: [transformResponse],
headers: { 'Content-Type': 'application/vnd.api+json' },
});
And then call this function to set headers dynamically
agent.defaults.headers.common['Authorization'] = `JWT ${localStorage.getItem('token')}`;
Then call methods of your axios instance to make API calls
agent.get(`${endpoint}search`, { params }),
agent.post(`${endpoint}search`, JSON.stringify(body)),

Mailchimp api to subscribe using java script request issue

I am trying below javascript code to subscribe on mailchimp. flow wise working good but i am getting error like not authorize because may be i am not passing api key correctly. please help to solve my issue
var request = new Request('https://<dc>.api.mailchimp.com/3.0/lists/[listid]/members', {
method: 'POST',
mode: 'no-cors',
json: {
"email_address": "am_it#live.com",
"status": "subscribed",
},
redirect: 'follow',
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': 'Basic apikey'
})
});
// Now use it!
fetch(request).then(function (data) {
console.log(data);
});
You need to add your authentification details with your username and api key. You can do it with the auth parameter:
auth: {
'user': 'yourUserName',
'pass': 'yourApiKey'
}
Just add that to your request object:
Request('https://<dc>.api.mailchimp.com/3.0/lists/[listid]/members', {
method: 'POST',
mode: 'no-cors',
json: {
"email_address": "am_it#live.com",
"status": "subscribed",
},
redirect: 'follow',
headers: new Headers({
'Content-Type': 'application/json',
'Authorization': 'Basic apikey'
}),
auth: {
'user': 'yourUserName',
'pass': 'yourApiKey'
}
});
I looked at the documentation in the getting started section of the developer mailchimp api: here and I converted the curl examples to javascript code using this page. Let me know if it worked.

Categories

Resources