Cannot connect to Meaning Cloud API: key missing - javascript

I have tried connecting to the API but for some reason it says I am missing the key. I am including the key and when I log it in the console, I see the correct value. Even I test the value of the API key that is logged, in the Meaning Cloud test tool, and it works correctly. Since at the moment is only a test, I have added directly a URL of an article that I want to check with the API.
Test API: https://learn.meaningcloud.com/developer/sentiment-analysis/2.1/console
I am using axios but I also tried with node-fetch and got the same result.
Here is the full code of the project in Github:
https://github.com/schilate68/Natural_Language_Processing/blob/master/src/server/index.js
app.post('/test', function (req, res) {
console.log("In POST test API");
console.log(process.env.API_KEY);
axios
.post('https://api.meaningcloud.com/sentiment-2.1', {
key: process.env.API_KEY,
url: 'https://blog.logrocket.com/complete-guide-flutter-architecture/',
lang: "en"
})
.then(res => ({
status: res.status,
body: res.data
}))
.then(({ status, body }) => console.log(status, body))
.catch(error => {
console.error(error)
})
})

Related

Next.js API routes all return "Interval Server Error" in production, but all the routes work in development

Whenever I go to any API route in my Next.js app in production it returns a 500 "Internal Server Error" but in development, all of them work completely fine and show/return what I expect them to.
I am deploying with an AWS Ec2 instance.
the code is available here: https://github.com/123om123/NFT-Marketplace
These are all my API routes.
The [...auth0].js creates the following routes:
/api/auth/login,
/api/auth/logout,
/api/auth/callback, and
/api/auth/me
If I try to access the "find_account" API route like the following:
let findAccount = async function () {
await fetch("/api/find_account", {
method: "POST",
body: JSON.stringify({
DBUrl: DBUrl,
user_id: user.sub,
}),
})
.then(async (response) => {
await response.json().then((result) => {
accountData = result;
if (accountData.data.allAccounts.nodes[0].addresses !== null) {
setAddressList(accountData.data.allAccounts.nodes[0].addresses[0].split(","));
}
});
})
.catch((err) => {
return err;
});
};
which handles requests like the following:
export default function handler(req, res) {
req.body = JSON.parse(req.body);
fetch(req.body.DBUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
query: `query MyQuery {
allAccounts(condition: {userId:"${req.body.user_id}"}) {
nodes {
addresses
}
}
}`,
}),
})
.then((response) => {
response.json().then((response) => {
res.status(200).send(response);
});
})
.catch((err) => {
res.status(500).send(err);
});
}
it works fine and returns the response from the graphql API in development, but in production it shows the above error.
The problem seems to be that the API routes aren't even created and are therefore inaccessible. All the API routes worked a few weeks ago, but now they seem to have stopped working.
Check out this answer, it helped me solve a bug similar to yours. In my case when vercel was deploying my PR branch I was getting a 500 Internal Error. Once I merge the PR into main and vercel does a fresh deployment, I was now getting a 504 gateway error. The answer below helped me find out why.
https://stackoverflow.com/a/68774331/12775824

How to write an Axios get request with a query?

I am using the MERN-Stack (React, NodeJS, React, Express, + MongoDB). I want to write a get-request with Axios to call up a route in the backend. But I only want to retrieve specific data from my database. For that I want to use a query.
My URL looks something like this:
'http://localhost:5000/users?name=john'
So I only get users whose name is John.
I wrote an axios-request, which looks like this:
axios
.get("http://localhost:5000/user/getown", { params: { username: this.state.username } })
.then((response) => {
this.setState({ users: response.data });
})
.catch((error) => {
console.log(error);
});
I am not sure if I pass the query correctly.
In the backend I am using Express and Mongoose to get the date from my MongoDB. Therefore I am using this code:
router.route("/getown").get((req, res) => {
User.find({ username: req.query.username })
.then((user) => res.json(user))
.catch((error) => res.status(404).json("Error: " + error));
});
When I test the '/getown' route with Insomnia everything works correctly, so I think the mistake is in the frontend.

I have a NodeJS backend I am developing to work alongside a ReactJS frontend but I keep getting a 500 error

I am testing my NodeJS backend using Insomnia and while it does work no problem in Insomnia I am getting a 500 error on the frontend every time. I was wondering if anyone maybe knew where this could be coming from if like I said it works just fine on my the endpoint testing program. Since it is a 500 error it is not very descriptive. Links can be shared if needed
const handleSubmit = e => {
e.preventDefault();
console.log("cred username", creds.username);
axios
.post("https://exampleapi/api/login")
.then(res => {
console.log(res.data);
localStorage.setItem("token", res.data.access_token);
props.history.push("/");
})
.catch(err => console.log(err.response)); };
So I figured it out it was an error in my post request would should have been included was
const handleSubmit = e => {
e.preventDefault();
console.log("cred username", creds.username);
axios
.post("https://mystery-doggo.herokuapp.com/api/login", creds)
.then(res => {
console.log(res.data);
localStorage.setItem("token", res.data.payload);
props.history.push("/");
})
.catch(err => console.log(err.response));
};
"creds" after the link and change res.data.access_token to res.data.payload

Saving data from JSON end point

I am trying to map over the returned json and save the id into profile/profiles. However it does not seem to be mapping over the the data correctly, id: ${ profile.id } this bit needs to be changed? Any help is much appreciated.
Is their a online tool that can help with me this?
API request:
// Grabs company data from the json url
private getProfiles() {
let config = {
headers: {'Authorization':'Bearer AQVVEqNXTWVYPpPYivKNWVO8jsTx2eveV3kBg'}
}
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response =>
response.data.map(profile => ({
id: `${ profile.id }`
}))
)
.then(profiles => {
this.setState({
profiles
});
})
// We can still use the `.catch()` method since axios is promise-based
.catch(error => this.setState({ error, isLoading: false }));
}
Json data returned:
{
"localizedLastName": "King",
"id": "fm0B3D6y3I",
"localizedFirstName": "Benn"
}
When I console log the response.data
If the only data returned from your endpoint is the JSON you posted, then you don't have an array to map over.
You have a single object.
I've never used the axios library before, but looking at the source code response.data should be the JSON-parsed responseText from the XHR request:
https://github.com/axios/axios/blob/4f189ec80ce01a0275d87d24463ef12b16715d9b/lib/adapters/xhr.js#L51-L53
https://github.com/axios/axios/blob/4f189ec80ce01a0275d87d24463ef12b16715d9b/lib/defaults.js#L61
And now I see that you have posted response.data and it matches what I'd expect.
With that in mind I'd suggest handling it like this:
// Grabs company data from the json url
private getProfiles() {
let config = {
headers: {'Authorization':'Bearer AQVVEqNXTWVYPpPYivKNWVO8jsTx2eveV3kBg'}
}
axios
.get("https://cors-anywhere.herokuapp.com/" + "https://api.linkedin.com/v2/me", config)
.then(response => ({
id: profile.id
}))
.then(profiles => {
this.setState({
profiles
});
})
// We can still use the `.catch()` method since axios is promise-based
.catch(error => this.setState({ error, isLoading: false }));
}
What you're getting back is a single profile though. If you need profiles to be an array you'll need to put the response in an array.
I don't get it, what you are trying to do. In the map you have a callback function, but as I see you wrote there an object. If you are wanting to rewrite the current profile's id then write this:
response.data.map(profile => ({
profile.id = `${ profile.id }`;
}))
But if you want it to make a variable then this:
response.data.map(profile => ({
let id = `${ profile.id }`;
}))

Fetch POST Unexpected end of input Erorr

I'm trying to do a POST request for authentication in Redux and I'm passing email & password as the body but it returns this error in the console:
Uncaught (in promise) SyntaxError: Unexpected end of input
I looked around for the answer and many people suggested that it might be a missing } brace but I looked for it and I don't think it's that.
Here is my fetch function.
export function loginUser(creds) {
let config = {
mode: 'no-cors',
method: 'POST',
headers: { 'Content-Type':'application/x-www-form-urlencoded' },
body: `email=${creds.email}&password=${creds.password}`
};
return dispatch => {
dispatch(requestLogin(creds));
return fetch('http://localhost:4000/api/authenticate', config)
.then(response =>
response.json()
.then(user => ({ user, response }))
).then(({ user, response }) => {
if (!response.ok) {
dispatch(loginError(user.message));
return Promise.reject(user);
} else {
localStorage.setItem('id_token', user.token);
dispatch(receiveLogin(user));
}
});
};
}
The fetch POST method calls the API and I see it in the networking tab and I see the response too but the fetch request stops at .then(response => after the url and config.
It's been two days and still can't find the solution. By the way, this works fine in Postman(chrome extension), so nothing wrong with the API.
Thanks
Answer EDIT: The issue was related to CORS, so for anyone having the same issue as I did.
I solve the same question when I remove
mode: 'no-cors'
from the config.
Anyway you could simplify your snippet code to:
fetch('http://localhost:4000/api/authenticate', config)
.then(response => response.json())
.then(({ user, response }) => {
And you should might add catch method to handle an Error object.

Categories

Resources