Nodejs Error: Cannot GET/ on app.post command [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 days ago.
Improve this question
This code is of an express server that handles API requests.
app.get('/') gives the desired result (hello world page). Changing app.get to app.post raises Cannot GET/
I was expecting a window pop up with a Hello World! message along with an input field.
import React, { useState } from 'react';
import './App.css';
function App( ) {
const [message, setMessage] = useState('');
const [response, setResponse] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
fetch('http://localhost:3001/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({message})
})
.then(res => res.json())
.then(data => setResponse(data.message));
}
return (
<div className="App">
<form onSubmit={handleSubmit}>
<label>
Message:
<textarea value={message} onChange={e => setMessage(e.target.value)} />
</label>
<input type="submit" value="Submit" />
</form>
<div>
continue
{response}
</div>
</div>
);
}

Since the error says Cannot GET/ while you're running a POST request, you've incorrectly called the API.
Your server-side code is correct and other details in the question are irrelevant. From where you're calling the API, change the method from GET to POST and it should work as expected.

As hopefully you are aware you have frontend and a backend. Front end is your react app, backend is your express server. Your react app is calling your express server (API) via fetch I assume? Ensure the fetch request is making a post request correctly with correct headers
Also ensure CORS is handled correctly and your react app and express server are running on separate ports. React by default is 3001, run your express server on 4000 etc

Related

I do not know why I can't access open ai's api for use in a react app

I am trying to access openai's api for a react application. I am getting an "unsafe header" error, an error 400, and at the same time "https://api.openai.com/v1/completions" is sending me a prompt about not providing my api key, even though I am providing the api key through a .env file. I do not know what to do, and I'm wondering what exactly I did wrong.
This is the react function I am using:
const configuration = new Configuration({
apiKey: process.env.REACT_APP_OPENAI_API_KEY,
organization: "org-xut9Kn1LqNLyDiHEMAQlnJ0k"
});
const openai = new OpenAIApi(configuration);
const handleSuggestions = async (text) => {
const response = await openai.createCompletion({
model: "text-davinci-001",
prompt: "autocomplete this word, letter or sentence: " + text,
max_tokens: 100,
n: 1,
stop: text.length - 1,
temperature: 0.15,
});
console.log(response);
const data = await response.json();
setSuggestions(response.choices[0].text.split(' ').slice(text.split(' ').length - 1).join(' ').split(' '));
};
``
I am getting a "unsafe header "User-Agent"" error as well as an error 400 from "https://api.openai.com/v1/completions" in my browser console while running the react app. This is the full prompt I am getting back from "https://api.openai.com/v1/completions":
{
"error": {
"message": "You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY), or as the password field (with blank username) if you're accessing the API from your browser and are prompted for a username and password. You can obtain an API key from https://platform.openai.com/account/api-keys.",
"type": "invalid_request_error",
"param": null,
"code": null
}
}
Please what can I do, and what exactly is wrong with the code? Also, hoping this counts as a "Minimal, Reproducible Example", as I am pretty new to stack overflow.
You should be making the request from a server not your client.
Ajax request: Refused to set unsafe header
I highly recommend checking out Next.js 13 as it uses React under-the-hood and let's you create "Server" components that are essentially isomorphic.
Here's an example Next.js 13 app/pages.tsx file:
const App = async () => {
console.log("App.js");
const results = await fetch(
`http://api.weatherapi.com/v1/forecast.json?key=<API_KEY>&q=Stockholm&days=6&aqi=no&alerts=no`
);
const json = await results.json();
console.log("json", json);
return (
<>
<h3>{json.location.name}</h3>
<p>{json.location.temp_c}</p>
<p>{json.location.localtime}</p>
</>
);
};
export default App;
Check out this working Next.js 13 / React18 sandbox which hits the Weather API - If you'd like fork it and see if your API calls work on the server inside this app.pages.tsx file. Otherwise you will need to use a Firebase Function or some backend server.

Why does Axios keep sending Network error on React Native

I am currently working on a React Native project.
My code is this:
const onSubmit = async ({email, password}) => {
const url = 'https://gravitee.****.com:***/***/api/auth/signin';
try {
const response = await axios.post(url, {
email,
password,
registrationSource: SOURCE,
});
console.warn(response);
} catch (error) {
console.warn('err: ', error);
}
};
I have made this project on React as well and this is working well there. But on React Native it gives me Network Error. Nothing else. I tried with fetch api, it didn't work either. And what's interesting is I can fetch data from an external api that I just found on web. So what could be the problem? By the way i am running app on ios simulator and my device is Mac M1
Full error is like this:
err: AxiosError: Network Error
Call Stack
onSubmit
index.js: 87:7
asyncGeneratorStep
asyncToGenerator.js: 3:16
\_throw
asyncToGenerator.js: 29:27
tryCallOne
internalBytecode.js: 53:16
anonymous
internalBytecode.js: 139:27
I tried sending request to gravitee with axios and fetch and expecting login data of the user.

request failed with status code 403(forbidden) in axios.get

i am building a simple lyrics finder app using react.js and using musixmatch api. when i request the api i get this error in consoleError: Request failed with status code 403 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:62)
this is my componentDidMount() function
import React, { Component } from 'react';
import axios from 'axios';
const Context = React.createContext();
export class Provider extends Component {
state = {
track_list: [],
heading: "Top 10 Tracks"
}
componentDidMount() {
axios.get(
`https://cors-anywhere.herokuapp.com/https://api.musixmatch.com/ws/1.1/chart.tracks.get?chart_name=top&page=1&page_size=5&country=it&f_has_lyrics=1&apikey=${
process.env.REACT_APP_MM_KEY}`
)
.then(res => console.log(res.data))
.catch(err => console.log(err));
}
render() {
return (
<Context.Provider value={this.state} >
{this.props.children}
</Context.Provider>
);
}
}
export const Consumer = Context.Consumer;
status code 403 means that you are not authorized. You could either have entered a wrong api key or maybe your process.env does not work (try to enter the api key directly!).
And are u sure that you need cors-anywhere? Did you try without?
EDIT:
you can test if your api key works when you simply enter the url with your key into the browser (without cars-anywhere) like so:
https://api.musixmatch.com/ws/1.1/chart.tracks.get?chart_name=top&page=1&page_size=5&country=it&f_has_lyrics=1&apikey=your_api_key
EDIT 2:
this works, when I try it inside a React application: So the problem must be at your process.env implementation.
componentDidMount() {
axios.get(
`https://cors-anywhere.herokuapp.com/https://api.musixmatch.com/ws/1.1/chart.tracks.get?chart_name=top&page=1&page_size=5&country=it&f_has_lyrics=1&apikey=your_api_key`
)
.then(res => console.log(res.data))
.catch(err => console.log(err));
}
From my experience, it was problem with axios version. so if you tried all solutions and still can not find the root cause, you can try to change axios version. I was using was assume role credentials to make a request against a service and always getting rejected with 403 even though the credentials were correct. I was using axios 1.3.1 but then I downgraded it to 0.27.2 and now my code is working fine
If you are not using an API key, you might have exhausted your request. You only get about 50 request thereabout per hour or something like, except you use an API key

Api is not fetching in reactJs

I am trying to fetch food by its key. In postman api is working fine but is the forntend it has no response.
backend code
app.get('/foods/:key', (req, res) => {
foodsCollection.find({ key: req.params.key }).toArray((err, documents) => {
res.send(documents[0])
})
})
frontend code
const { key } = useParams()
const [foodById, setFoodById] = useState({})
useEffect(() => {
fetch(`http://localhost:5000/foods/${key}`)
.then((res) => res.json())
.then((data) => {
setFoodById(data)
})
}, [key])
Although you've added some images above, the most important is missing, namely, what are the Browser's Developer Tools stating the problem is. You should see some message in the Console tab, as well as in the Network tab for that particular request, if it is indeed being made. Until anyone sees this, it will be very difficult to help in fixing your problem.
If your not already, I suggest scaffolding any react app with create-react-app (CRA). This will give you a working app to start from. You can ignore CORS related issues in development, if using CRA, by adding "proxy": "http://localhost:5000", to your package.json file, see here for more on this method, but remember, this is only works for local development. You can also start Chrome to ignore Web Security by running it with the --disable-web-security flag e.g. chromium --disable-web-security, but that isn't a great idea really, more a way to quickly determine if you are having CORS problems, as Chrome masks some problems as CORS related, when in fact they aren't.
I'd also suggest changing your fetch code to use await, so instead you'd have:
const response = await fetch(`http://localhost:5000/foods/${key}`);
if (!response.ok) {
console.error(`Error message: ${response.statusText} ${response.status}`);
}
const result = response.json();
console.log(result);
This isn't necessary, but I've always found it way easier to read than the then/catch/finally method.
Reason for error
You need to stringify an object before sending it to the client with the JSON.stringify() method. When we exchange data to/from a web server, it must be a string.
Solution:
Proper way to send response to the client would to wrap the entire API in a try-catch block and explicitly specify the HTTP Status Code along with the stringified data in every response.
Note: Although 500 status code is used for error handling, you should choose one as per the use case.
app.get('/foods/:key', (req, res) => {
try {
/*
rest of the code
*/
foodsCollection.find({ key: req.params.key }).toArray((err, documents) => {
if (err) {
// 500 stands for internal server error
return res.status(500).send(JSON.stringify('Here goes a meaningful error message!'));
}
// 200 stands for success
res.status(200).send(JSON.stringify(documents[0]));
});
/*
rest of the code
*/
} catch (error) {
// 500 stands for internal server error
res.status(500).send(JSON.stringify('Here goes another meaningful error message!'));
}
})
The problem is that you haven't set the CORS headers of response in your backend code. and you are using different ports in your backend and frontend (5000 & 3000) so the Same Origin Policy disallows reading the remote resource, indicating that the request was blocked due to violating the CORS security rules.
you've to set the CORS headers.
you can install the CORS npm package and follow it's instructions to resolve the issue like this:
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
.
.
.
And one other issue that I'm seeing is that you've put the react-router default route before your specified path. so move the <route path="*"> after <route path="/foods/:key">

Rails API not returning JSON to React frontend

I have written a Rails API backend. I can see that the endpoint is getting hit by watching my server in my terminal. I can also see a return in Postman. However, I am unable to get a payload returned in my React frontend. Here is my fetch call in React(I have the debuggers in there but they're not getting hit):
handleSearch(video) {
fetch(`http://localhost:3000/api/v1/search?q=${video}`)
.then((response) => {
debugger
return response.json()
})
.then((data) => {
debugger
})
}
Here is my api controller:
def index
videos = VideoService.search_content(params['q'])
render json: videos
end
And here's my output in my terminal server:
Started GET "/api/v1/search?q=Firefly" for 127.0.0.1 at 2017-12-28 11:40:38 -0700
Processing by Api::V1::SearchController#index as */*
Parameters: {"q"=>"Firefly"}
Completed 200 OK in 426ms (Views: 7.5ms | ActiveRecord: 0.0ms)
I'm not really sure what the problem is. I have never had an issue before when making api requests. And like I said. I can see the server being interacted with and can see a payload return in Postman. Thanks for any help!
EDIT:
Here is how I'm calling the handleSearch on the way down:
<SideBar
info={this.state.info}
logout={this.handleLogout.bind(this)}
search={this.handleSearch.bind(this)}
/>
And here it is being called in the SideBar component:
searchHandler(video) {
this.props.search(video)
}
<SearchBox search={this.searchHandler.bind(this)}/>
And finally where the input is actually coming in:
handleSearch(e){
let video = e.target.previousSibling.value
this.props.search(video)
}
render() {
return(
<form className="search-box" >
<input type="text" placeholder="Search.." name="search"/>
<button className="fa fa-search" type="submit" onClick={this.handleSearch.bind(this)}>
</button>
</form>
)
}
Missing e.preventDefault() I'm new to React and thought it was handled behind the scenes by React.

Categories