Next Js API not posting to an external API - javascript

so i was trying to make 2 different projects first one is my ecommerce frontend made with next js and second one is ecommerce dashboard which is also made with next js.
But when i am trying to post products from my dashboard to my ecommerce frontend nothing is happening even also I am not getting any error in console that's why i am unable to understand what is the problem.
Can anyone help me in this ? The fetch code is below.
const handelSubmit = async (e) => {
e.preventDefault();
console.log("clicked");
fetch(`http://192.168.43.53:3000/api/products`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(
name,
price,
// mediaUrl,
description,
collect,
),
})
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>

Nextjs apis only work with the same origin by default, see Nextjs api Caveats for more info.
If you want to make a fully public api with Nextjs, you have to add cors, see Api Middlewares. Your code will look something like:
import Cors from 'cors'
// Initializing the cors middleware
const cors = Cors({
methods: ['GET', 'HEAD'],
})
// Helper method to wait for a middleware to execute before continuing
// And to throw an error when an error happens in a middleware
function runMiddleware(req, res, fn) {
return new Promise((resolve, reject) => {
fn(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
If your backend api isn't defined with Nextjs, please share the code of your requested api endpoint and also the technology it uses.

I think the data you are posting needs to be in JSON first.
body: JSON.stringify(
key:value,
key1:value1
)

Related

Make synchronous post request from react to flask to get dict

Context:
I'm building a app that can plot graph structures in electron with react. My backend is some Matlab code that can perform analysis on the graph struct. I'm using flask as the middle man communicating between them.
In the GUI i have a button that should be able to load the data that is provided in a excel file to the GUI. This should be done by a post request that uses a matlab script to load the data from the excel file and then returns this to javascript.
I have tried using something like this:
fetch('http://localhost:5000/getGriddata', {
method : 'POST',
headers : {
'Content-Type' : 'application/json'
},
body : JSON.stringify(fileObj.path)
}).then(response => response.json())
.then(data => setGriddata(data))
.catch(error => console.log(error));
The problem is that this code won't wait for the flask function to be finished. The flask function takes about 10 seconds depending on the graph size. Therefor i want to make this call in sync with my javascript code so that after the request, i can assure that the new griddata is defined.
Question:
Is there some way to ensure this when using fetch?
Do i need to find a different way of connecting to flask, if so what would that be?
Solution:
Instead of using the fetch api, another post brought me to the XMLHttpRequest. This works synchronously if the parameter is set to false.
With this my code looks like this:
var request = new XMLHttpRequest();
request.open("POST",'http://localhost:5000/getGriddata',false);
request.setRequestHeader('content-type', 'application/json');
request.send(JSON.stringify(fileObj.path));
console.log(request.response)
console.log(request.responseText)
setGriddata(JSON.parse(request.responseText))
Instead of using callbacks, try using async/await
const fetchGridData = async () => {
try {
const response = await fetch('http://localhost:5000/getGriddata', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(fileObj.path)
});
const result = await response.json();
setGriddata(result)
} catch(error) {
console.error("fetchGridData =>", error)
}
}

When to set the headers explicitly when making HTTP request in NodeJS application

So I was having a look at a codebase of a NodeJS application and there were some specific functions making HTTP requests to the backend. To be exact, those functions were making a GET request to the backend and one thing that I found confusing was that in some of the functions, the headers were mentioned explicitly whereas, in some other functions who were making the GET request, there was no mention of headers (i.e. headers were not being set explicitly). Below is an example:
In the code below, the function is making a GET request and there's no mention of headers (i.e. the headers are not being set explicitly):
// Method for fetching a single post from the backend on the basis of the post ID
export const singlePost = (postID) => {
return fetch(http://localhost:8080/post/${postID}, {
method: "GET",
})
.then((response) => {
return response.json();
})
.catch((error) => {
console.log(error);
});
};
In the code below, the function is making a GET request and the headers are being set explicitly:
// Helper Method for making the call to the backend and fetching all their details of all the posts
export const list = (page) => {
return fetch(http://localhost:8080/posts/?page=${page}, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
})
.then((response) => {
return response.json();
})
.catch((error) => console.log(error));
};
Now coming to the main question, could someone please explain to me when are we supposed to set the headers explicitly not only in just GET request but in other general HTTP requests as well (i.e. POST, PUT, OPTION etc).
It would be really great if some could refer a source or explain this concept here. Thanks!
HTTP request header is the information, in the form of a text record, that a user's browser sends to a Web server containing the details of what the browser wants and will accept back from the server. The request header also contains the type, version and capabilities of the browser that is making the request so that server returns compatible data.
Check this https://code.tutsplus.com/tutorials/http-headers-for-dummies--net-8039

Is it possible to send delete/put requests to a Azure AD secured api or get jwt Token as String using aadHttpClientFactory

I have a custom Api which I secured with Azure AD like the following tutorial:
https://learn.microsoft.com/en-us/sharepoint/dev/spfx/use-aadhttpclient
Thats working great.
now I have the following Code to make a GET request to my custom API (working):
this.context.aadHttpClientFactory
.getClient('MY_API_URL')
.then((client: AadHttpClient) => {
console.log(AadHttpClient.configurations.v1);
return client
.get(
`MY_API_URL/SOME_ROUTE`,
AadHttpClient.configurations.v1
);
})
.then(response => {
var res= response.json();
return res;
}).then( (res: any[]) => {
...
HERE I WOULD LIKE TO GET MY TOKEN
});
So this is working how I expect it to work.
But the aadHttpClientFactory only supports GET and POST requests
Now my Idea was to just make some PUT/DELETE requests with jQuery and use the Bearer token I got above (tested with postman and its working).
But then I realised, that I won't get the token that easy.
When I console.log(AadHttpClient.configurations.v1) I only get this:
Sure I could just change my API to use POST instead of PUT/DELETE but that would be pretty ugly
Does anyone has an Idea on how I could get the token as a String to do custom requests with it?
AadHttpClient supports the fetch(url, configuration, options) method, where options can include all of the request configuration options supported by the Fetch API.
So, to make a DELETE request, you would do something along the lines of:
client
.get(
`MY_API_URL/SOME_ROUTE`,
AadHttpClient.configurations.v1,
{
method: 'DELETE'
}
);
I solved it now.
Maybe my answer will help someone later.
according to philippe Signoret's answer the is the fetch() function.
I had to use it like following:
this.context.aadHttpClientFactory
.getClient(api_url)
.then((client: AadHttpClient) => {
return client
.fetch(
MY_URL,
AadHttpClient.configurations.v1,
{
method: METHOD, //put/DELETE etc.
headers: [
["Content-Type", "application/json"]
],
body: JSON.stringify({
YOUR REQUEST BODY
})
}
)
});

Javascript AzureAd Consume Rest Service

RestAPI: I have a Rest API running Asp Core with AzureAd Authentication.
WebApp: I have a separate WebApplication running Asp Core as backend, with Javascript frontend.
The WebApp backend authenticates through AzureAd, and then against the RestAPI to check if a user is registred.
I want the javascript client to be able to consume the Rest API directly. How should i go about this without exposing the accesstoken?
I could go about sending the request from Javascript to WebApp Backend -> Rest API. But i really want to avoid this, because of unnecessary code.
In this scenario, you can try to implement ADAL for js in your JS client. Leveraging **adal** to gain the authentication token, and when you call your Web Api, it will add the authentication header in HTTP requests.
E.G.
Suppose we want to call the Microsoft Graph API from our JS client.we develop a node.js script that uses request to call the Microsoft Graph API for groups to create a new Security Group.
The following code shows how the API is consumed from that script. Note that the token and the name are passed by parameter. Additionally, this function returns a Promise that is successfully resolved when the group is correctly created and rejected when is not.
var request = require('request');
function createGroup(token, name) {
return new Promise((resolve, reject) => {
const options = {
method: 'POST',
url: 'https://graph.microsoft.com/v1.0/groups/',
headers: {
'Authorization': 'Bearer ' + token,
'content-type': 'application/json'
},
body: JSON.stringify({
"displayName": name,
"mailEnabled": false,
"securityEnabled": true
})
};
request(options, (error, response, body) => {
const result = JSON.parse(body);
if (!error && response.statusCode == 204) {
resolve(result.value);
} else {
reject(result);
}
});
});
}
In order to call Microsoft Graph API, we needed to be authenticated and that is why in the previous section we have a token as a parameter of the function which was used to perform the request.
we should add the following code to generate the token. Note that we are using the adal npm package to do this easier, calling the acquireTokenWithClientCredentials method of the AuthenticationContext object. Additionally, we have some constants that need to be updated with the client id and secret obtained before as well as the tenant name.
var adal = require('adal-node');
const TENANT = "{tenant-name-here}.onmicrosoft.com";
const CLIENT_ID = "{Application-id-here}";
const CLIENT_SECRET = "{Application-key-here}";
function getToken() {
return new Promise((resolve, reject) => {
const authContext = new adal.AuthenticationContext(`https://login.microsoftonline.com/${TENANT}`);
authContext.acquireTokenWithClientCredentials(GRAPH_URL, CLIENT_ID, CLIENT_SECRET, (err, tokenRes) => {
if (err) { reject(err); }
resolve(tokenRes.accessToken);
});
});
Hope it helps.

Vue.js, Axios multiple get CORS requests to Laravel API are randomly failing

I have this problem - on Vue component created life cycle hook I am making 2 CORS get requests via Axios to external Laravel API. If I make only one of the requests everything is fine and it works 100% of the time. But if I make 2 or more requests I sometimes get failed requests on random in the network tab. Obviously I am doing something wrong with Axios. Can you please help me.
This is my component created hook - I call VueX actions.
created () {
this.$store.dispatch('getPets');
this.$store.dispatch('getSpecies');
},
And this are my actions in VueX store
actions: {
getPets(context) {
return new Promise((resolve, reject) => {
axios.get('api/pets')
.then(response => {
context.commit('SET_PETS', response.data);
context.commit('SET_SELECTED_PET', response.data.data[0]);
resolve(response);
})
.catch(error => {
reject(error);
});
});
},
getSpecies(context) {
return new Promise((resolve, reject) => {
axios.get('api/species')
.then(response => {
context.commit('SET_SPECIES', response.data);
resolve(response);
})
.catch(error => {
reject(error);
});
});
},
setSelectedPet(context, pet) {
context.commit('SET_SELECTED_PET', pet);
},
}
Then I get failed requests on random - sometimes both requests are ok (200 status),
other times one of them is failing...
Requests
The request is failed - there is no response, I think that the request does not go to the Laravel API at all. Laravel logs are empty too.
I think I am doing something wrong with Axios, because its not from my browser or firewall - I have stopped firewall and tested in incognito and other browsers without any extensions. Any help will be appreciated.
This are the Axios headers I set up in the main js file.
// Set axios to call the backend API and set its headers on every page reload
window.axios = require('axios');
window.axios.defaults.baseURL = 'http://api.aaa';
window.axios.defaults.timeout = 30000;
window.axios.defaults.headers.common = {
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer '+getToken(),
};
Ok, after some time I finally figured it out. It was the PHP opCache that was causing this behavior. If you have the similar problem just turn opChache off.
Btw can you give me your thoughts about what can cause this behavior from Laravel because I dont want to lose opCache as an option for similar Laravel projects?

Categories