This is a simple Post request using Axios inside Vue:
import axios from 'axios'
export default {
name: 'HelloWorld',
props: {
msg: String
},
mounted () {
const code = 'test'
const url = 'http://localhost:3456/'
axios.post(url, code, { headers: {'Content-type': 'application/x-www-form-urlencoded', } }).then(this.successHandler).catch(this.errorHandler)
},
methods: {
successHandler (res) {
console.log(res.data)
},
errorHandler (error) {
console.log(error)
}
}
}
The Get method works fine. But Post stay as "Pending" on Network tab. I can confirm that there is a Post method on my webservice and it return something (tested on Postman).
UPDATE
Sending code as a param:
axios(url, {
method: 'POST',
headers: {
'content-type': 'application/json',
},
params: {
code : 'test'
},
}).then(this.successHandler).catch(this.errorHandler)
WEBSERVICE
server.post('/', (req, res, next) => {
const { code } = req.params
const options = {
validate: 'soft',
cheerio: {},
juice: {},
beautify: {},
elements: []
}
heml(code, options).then(
({ html, metadata, errors }) => {
res.send({metadata, html, errors})
next()
})
})
I think there's issue with your axios request structure.
Try this:
const URL = *YOUR_URL*;
axios(URL, {
method: 'POST',
headers: {
'content-type': 'application/json',
},
data: *YOUR_PAYLOAD*,
})
.then(response => response.data)
.catch(error => {
throw error;
});
If you're sending a query param:
axios(URL, {
method: 'POST',
headers: {
'content-type': 'application/json',
},
params: {
code: 'your_string'
},
})
if it is path variable you can set your url:
const url = `http://localhost:3456/${code}`
Let me know if the issue still persists
I also was facing the same. Network call was pending all the time and Mitigated it by passing the response back from server.js(route file) e.g(res.json(1);) and it resolved the issue
Related
I am trying to send the username of a logged-in person from the Client to the Server as a string. I am already sending a file (image) but I also want to send a string as well.
Essentially what I wanna do is in the Server Side File to replace the 'public_id' with username from Client-side.
As you can see below I am already sending the image (file) that I want to the server. I have used console.log(loggedInUser?.username); to show the string that I want to be sent.
Hope this was enough to explain what I am trying to do. Thanks in advance.
Client Side file
console.log(loggedInUser?.username);
const uploadImage = async (base64EncodedImage: string) => {
try {
await fetch('/api/upload', {
method: 'POST',
body: JSON.stringify({ data: base64EncodedImage }),
headers: { 'Content-type': 'application/json' },
});
} catch (error) {
console.error(error);
}
};
Server side file
app.post("/api/upload", async (req, res) => {
try {
const fileStr = req.body.data;
const uploadedResponse = await cloudinary.uploader.upload(fileStr, {
upload_preset: "geekyimages",
public_id: "public_id",
invalidate: true,
});
console.log(uploadedResponse);
res.json({ msg: "Uploaded" });
} catch (error) {
res.status(500).json({ err: "Something went wrong" });
}
});
Just send both inside a single JSON-Object:
// client side
await fetch('/api/upload', {
method: 'POST',
body: JSON.stringify({
data: base64EncodedImage,
username: loggedInUser?.username
}),
headers: { 'Content-type': 'application/json' },
});
// server side
const username = req.body.username;
From here
await fetch('/api/upload', {
method: 'POST',
body: JSON.stringify({ data: base64EncodedImage }),
headers: { 'Content-type': 'application/json' },
});
Just add a username in the body like
await fetch('/api/upload', {
method: 'POST',
body: JSON.stringify({ data: base64EncodedImage, username: username: loggedInUser?.username || "SOME_DEFAULT_VALUE" }), // The default value is in case you an have a null or undefined username
headers: { 'Content-type': 'application/json' },
You can also prevent this behavior adding this check
if (loggedInUser?.username) ... // The code without default value
else { // A message }
I have form submit function with axios:
const onSub mit = (data) => {
const webhookUrl = 'MY URL';
const info = JSON.stringify(data);
axios({
method: 'post',
url: `${webhookUrl}`,
data: info,
config: { headers: { 'Content-Type': 'application/json' } },
})
.then(function (response) {
alert('Message Sent!');
})
.catch(function (response) {
//handle error
console.log(response);
});
};
and here is what i get after JSON.stringify inside info:
{"fullname":"Temirlan","email":"test#mail.com","phone":"0179890808","proffesion":false,"message":"test"}
This is what i get in my webhook after form is submitted which is wrong:
However if i use Thunder client and post same data:
I get it correctly:
What am i doing wrong?
So I used different approach with axios and it worked:
let axiosConfig = {
headers: {
'Content-Type': 'application/json;charset=UTF-8',
'Access-Control-Allow-Origin': '*',
},
};
axios
.post(webhookUrl, info, axiosConfig)
.then((res) => {
console.log('RESPONSE RECEIVED: ', res);
})
.catch((err) => {
console.log('AXIOS ERROR: ', err);
});
I have managed to make this run: How to modify axios instance after exported it in ReactJS?
And it looks like this:
import axios from 'axios';
import constants from '../constants.js';
import Cookies from 'js-cookie';
const API = axios.create({
baseURL: `${constants.urlBackend}`,
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
API.interceptors.request.use(
config => {
var accesstoken = Cookies.get('accesstoken');
if (accesstoken) {
config.headers.Authorization = `Bearer ${accesstoken}`;
} else {
delete API.defaults.headers.common.Authorization;
}
return config;
},
error => Promise.reject(error)
);
export default API;
And this is an example usage
getUserList() {
API.get('/userlist')
.then(response => {
this.setState({
userList: response.data
}, () => {
console.log(this.state.userList)
});
})
}
But now im confused because I dont understand how to use this with a post so I can pass some data to it, similar to this
axios({
method: 'post',
url: constants.urlBackend + "/register",
data: qs.stringify({ email, password }),
headers: {
'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
}
})
But using the above object.
API.post('/user/update/'+this.state.rowId).then(response => {
//some sort of body {email,password}
})
Have you tried
API.post(
'/user/update/' + this.state.rowId, {
email,
password
}).then(response => {})
$ajax server response:
{"username":"","password":""}
fetch server response:
{"{\"username\":\"\",\"password\":\"\"}":""}
Why aren't they the same? I need the same server response. I'm using PHP+Apache
Here is my code:
import $ from 'jquery';
export function FetchData(type, data){
const serverUrl = 'http://localhost/oms/'+ type + ".php";
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: serverUrl,
data //body : {username: "username", password:"password"}
})
.done(function(res) {
//console.log(res);
resolve (res);
})
.fail(function(jqXHR, exception){
//alert('server error()');
reject(jqXHR);
});
fetch(serverUrl,{
method: 'POST',
headers: {
Accept: '*/*',
'Content-Type': 'application/x-www-form-urlencoded',
//'Access-Control-Allow-Origin': '*',
//'Access-Control-Allow-Methods': 'POST,GET,OPTIONS,PUT,DELETE',
//'Access-Control-Allow-Headers': 'Content-Type,Accept',
},
body: JSON.stringify(data)
//body : {username: data.username, password: data.password}
})
.then((response) => response.json())
.then((responseJson) => {
resolve(responseJson);
})
.catch((error) => {
reject(error);
});
});
}
The responses are essentially the same just that response from fetch library returns a Stringified JSON.
You need to convert it into actual JS object.
const responseData = JSON.parse(response.json())
This occurs because you're sending the content type application/x-www-form-urlencoded with JSON data you need to change it to application/json like
export const FetchData = (type, data) => {
let serverUrl = 'http://localhost/oms/'+ type + ".php";
let data = {
username: data.username,
password: data.password
};
return new Promise((resolve, reject) => {
fetch(serverUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
credentials: 'include',
body: JSON.stringify(data),
})
.then((response) => response.json())
.then((responseJson) => {
resolve(responseJson)
})
.catch((error) => {
reject(error)
})
})
};
I added credentials it's read-only property of the Request interface indicates whether the user agent should send cookies from the other domain in the case of cross-origin requests. This is similar to XHR’s withCredentials flag
If you want to use something smaller to jQuery you can use Axios It's XMLHttpRequests
If you get some CORS issues this will help you
I am pretty new to react native. I am using react navigation in my react-native app. I am passing some props from one screen to another, and I need to use one of the props in a fetch I am trying to execute within the componentDidMount lifecycle method. With everything I have tried, it sends the value for the "type" key, but it sends nothing for the "location" key (see code below). Could someone help me with what am I missing or doing wrong? I have tried several things to pass the prop but nothing has worked yet.
componentDidMount() {
const { params } = this.props.navigation.state;
var data = {
type: 'r',
location: params.location
}
return fetch('http://myapisite', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
}
)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson,
}, function() {
// do something with new state
});
})
.catch((error) => {
console.error(error);
});
}
I was able to resolve the issue. I am not 100% certain why what I had didn't work, but when I changed it to the following, it worked as expected:
const {state} = this.props.navigation;
var data = {
type: 'restaurant',
location: state.params.location
}
return fetch('http://mylink', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
}
)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson,
}, function() {
// do something with new state
});
})
.catch((error) => {
console.error(error);
});