I was expecting the delete call
const userDeleteHandler = (id: number) => {
axios.delete('/admin/deleteUser/', {params: {UserID: id}})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
})
};
to work, but got a consistent 404 error. After some digging here I tried
axios.delete('/admin/deleteUser/'+ id)
which worked. Why did my params attempt not work?
Here is my server.ts settings
import adminRoutes from './routes/admin';
const app = express();
app.options('*', cors()) // include before other routes
app.use(cors( {origin: true}));
app.use('/admin', adminRoutes);
and the routes in my routes/admin.ts
router.get('/users', getAllUsers);
router.post('/newUser', postNewUser);
router.patch('/editUser', editUser);
router.delete('/deleteUser/:UserID', deleteUser);
Axios places the params like a query string with question marks (?). Therefore by using params, you are sending a request to /admin/deleteUser/?{id} which is not found
Because api is not found => 404
router.delete('/deleteUser/:UserID', deleteUser);
(you getting value as a param but you sending value as a query. if you remove /:UserID then it will work)
You should call like
axios.delete(/admin/deleteUser/${id})
(if you call API like above then it will work try this it will work definitely )
the reason not working is, You calling it only endpoint you should call API with-param (UserId is the param, not a query, just learn how to sent param value and query value this will make you understand )
Related
I am trying to add a dynamic route to the api folder for GET request.
In this scenario it works fine
api/[product]
const baseUrl ='https://myUrl'
const { product } = req.query
const url = `${baseUrl}/${product}`
And then testing http://localhost:3000/api/phone in Postman returns the correct result. So far it is fine.
Then, instead of fetching the api by product, I want my dynamic property to be filter values. Filter syntax provided by particular api looks like this ?$filter=name eq 'Milk'.
Filtering on frontend works fine when I test it in postman or in browser.
https://myUrl/phone?$filter=name eq 'iphone'
Now I try to do exactly the same as above, now in api folder. But it returns 404 This page could not be found..
api/[productType]
const baseUrl ='https://myUrl/phone?$filter'
const { productType } = req.query
const url = `${baseUrl}=${productType}`
In Postman I test it so:
`http://localhost:3000/api/phone=name-eq-'iphone'`
And get 404 response.
How to fix this issue? Any help will be appreciated.
I have created a demo at https://github.com/vercel-support/so-71663454-nextjs-route-poc with
// /api/[productType]
export default function handler (req, res) {
const baseUrl ='https://myUrl/phone?$filter'
const { productType } = req.query
const url = `${baseUrl}=${productType}`
res.json({ productType, query: req.query, url })
}
If you visit the link using https://so-71663454-nextjs-route-poc.vercel-support.app/api/phone=name-eq-'iphone'
You should be able to see the following result:
{
"productType": "phone=name-eq-'iphone'",
"query": {
"productType": "phone=name-eq-'iphone'"
},
"url": "https://myUrl/phone?$filter=phone=name-eq-'iphone'"
}
I want to post an id to the backend and get the expected result, so
here is the code in the frontend side :
import axios from "axios"
export async function getList(val) {
return await axios.post('http://localhost:5107/PlantsInfo', { id:val }).then(({ data }) => {
return data;
});
}
and in the backend, I have code something like this:
app.MapPost("/PlantsInfo", ([FromServices] DastShafaContext context, int? id) =>
{
// database interaction code according to the id
}
When I attempt this and check it by setting a breakpoint, it takes a request but without an id (that is null)...
But when I attempt to pass an id through Postman, everything is okay.
I think it seems the main problem is related to Axios.
How can I fix it?
This is how my problem was solved!
return await axios.post('http://localhost:5107/GetPlantInfoById?id=' + val).then(({ data }) => {
return data;
});
But this is not the standard way.
I still welcome the best way
I am trying to make the following call in React using axios:
axios.get(`http://localhost:5000/daily_batches/num_tweets_by_tag_and_date/`, {
params: {
tag: "Green/Sustainable Energy",
date: "2021-05-07"
}
})
.then(res => {
console.log(res)
})
Should I use req.params, req.body or req.query in my express route for the axios call to be successful? If I use req.params, like so:
router.route('/num_tweets_by_tag_and_date/').get(async (req, res) => {
try {
const tag = req.params.tag;
const date = req.params.date;
const tag_num_tweets_field = "tags." + tag + ".num_tweets"
const num_tweets_data = await DailyBatch.findOne({"date": date}, {[tag_num_tweets_field]: 1, "_id": 0});
res.json(num_tweets_data)
} catch (err) {
console.log(err)
res.status(400).json({
errors: {
global: "An error occurred."
}
})
}
});
I get a "data:null" as shown in this screenshot. And indeed by doing console.log(req.params.tag) and console.log(req.params.date) in the route I get "undefined"
If I use req.body.tag and req.body.date instead of req.params.tag and req.params.date, I still get "undefined" when I console.log(date) and console.log(tag). And the api response is still "data:null". However, in Insomnia the api call works just fine and returns the expected data, as shown in the pic below:
If I use req.query.date and req.query.tag, I successfully get the data in the axios api call I make in React. However, the call does not work in Insomnia, where I get "null".
I cannot seem to find a way to make the get call in React using axios and passing a dictionary with the call parameters, while at the same time being able to make calls to the same endpoint in Insomnia. The only way I found is to use req.param("tag") and req.param("date") but apparently it's deprecated and so I would not want to use that.
I have read multiple posts about req.params, req.body and req.query but the more I read about this the more I am getting confused. Any help would be appreciated!
Probably req.body.
req.params is used if you set up your route using variables, such as
router.get('/users/:id', (req, res)=>{})
you can console.log(req.body) to check.
req.params is used when you have dynamic route .
Example= /:num_tweets_by_tag_and_delete
check here: Node.js: req.params vs req.body
I'm deleting data from my firebase db with fetch but I can't figure out how to point to an exact ID.
const deleteHandler = async (id) => {
console.log(id);
await fetch(
`https://react-task-tracker-8e519-default-rtdb.firebaseio.com/tasks.json/${id}`,
{
method: "DELETE",
}
);
I tried it this way, but it gives me a CORS error.
I'm also displaying data from this db, that works fine.
UPDATE: I also want to say that when i console.log the id it gives me the correct one.
(Tl;dr: Try adding '.json' to the end of the endpoint.)
I would recommend reading this page to get a general understanding of what a CORS error is and why it might be happening.
In your case, I would recommend using the Firebase SDK that is best suited to your application. You could start here and follow the setup instructions for whichever is most applicable to your use case (perhaps the node client sdk)?
If you must avoid using the sdks for some reason then I would refer to some other Stackoverflow questions such as this one, which suggests that all Firebase REST endpoints need to end with '.json'.
You just need to add .json at the end of your request and remove .json from tasks.json. like this:-
await fetch(
`https://react-task-tracker-8e519-default-rtdb.firebaseio.com/tasks/${id}.json`,
const deleteHandler = async (id) => {
console.log(id);
await fetch(
`https://react-task-tracker-8e519-default-rtdb.firebaseio.com/tasks/${id}.json`,
{
method: "DELETE",
}
);
Just replace .json text with ${id}.json.
Have a nice day
Premise / What you want to achieve
React x Redux (port: 3000)
Go (port: 8080)
I am making a SPA.
I run into a CROS error when hitting the Go API.
I've encountered this problem many times, and every time I think it's solved, I hit a new API.
I should have made the basic settings, but I'm in trouble because I don't know what caused it.
We would appreciate it if you could help us.
Problem / Error message
Access to XMLHttpRequest at'http://localhost:8080/login' from origin'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No'Access-Control -Allow-Origin'header is present on the requested resource.
I encountered this when I hit the login API (post).
However, when I encountered this problem several times, I set cros on the header of api and axios side, and
Another get API avoided the error.
Also, when you hit api with postman, it becomes header
We have also confirmed that the header set in Go such as Allow-Origin is given without any problem.
Applicable source code
Header settings in Go
w.Header (). Set ("Content-Type", "application /json")
w.Header (). Set ("Access-Control-Allow-Origin", "http://localhost:3000")
w.Header (). Set ("Access-Control-Allow-Credentials", "true")
react axios settings
axios.defaults.baseURL ='http://localhost:8080';
axios.defaults.headers.post ['Content-Type'] ='application/json';
Posting code with an error
export const signIn = (email, password) => {
return async (dispatch) => {
try {
const response = await axios.post ('/login', {
email: email,
password: password,
});
const data = response.data;
dispatch (
signInAction ({
isSignedIn: true,
})
);
} catch (error) {
console.log (error);
}
};
};
Code hitting a successful getapi
useEffect (() => {
async function fetchTickers () {
try {
const response = await axios.get (`/ticker?Symbol=^skew`);
const data = response.data;
setChartAry ([... chartAry, [... data.daily]]);
} catch (error) {
console.log (error);
setChartAry ([]);
}
}
fetchTickers ();
}, []);
What I tried
I tried all the solutions that hit with stackoverflow etc. Also, considering the possibility of a problem with the browser itself, we also cleared the cache.
Is it the difference between axios by get and post? And how should I debug it?
I had this problem some time ago but I used Express for the backend, who knows this can solve your problem too.
try adding this to the axios settings axios.defaults.withCredentials = true;
You also need to allow the OPTIONS method for preflight requests
this article might help you solve the CORS problem on the backend: https://flaviocopes.com/golang-enable-cors/
The method was validated in gorilla / mux.
- r.HandleFunc("/login", app.loginHandler).Methods("POST")
+ r.HandleFunc("/login", app.loginHandler).Methods("POST", "OPTIONS")
We also had to deal with preflight.
if r.Method == "OPTIONS" {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:3000")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.WriteHeader(http.StatusOK)
return
}