I can get the data by request from this code.
let request = require('request');
let options = {
'method': 'POST',
'url': 'https://example.com/api',
'headers': {
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'client_id': '12345678',
'client_secret': 'abcdefg'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
However, I got '404.00.001' when I use "fetch" to access the same API. Is there any thing wrong in this code?
const fetch = require("node-fetch");
const url = "https://example.com/api";
var headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
var data = JSON.stringify( {
'client_id': '12345678',
'client_secret': 'abcdefg'
});
fetch(url, {method: 'POST', headers: headers, body: data})
.then(response => response.json())
.then((resp) => {
console.log(resp);
})
.catch(error => console.error('Unable to fetch token.', error));
'Content-Type': 'application/x-www-form-urlencoded' does not say JSON so why do you have var data = JSON.stringify?
The documentation tells you how to encode data as form parameters.
const { URLSearchParams } = require('url');
const params = new URLSearchParams();
params.append('a', 1);
Related
I have handleSubmit function that send two POST request, one for img upload and one for other information. I want to take the response from the img upload request and take the 'filename' and then store it in state so I can sent it with the other POST request.
Here is my Request Options
const postOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.serviceToken}`
},
body: JSON.stringify({
p_emp_id: empId,
p_pr_doc_type: docType,
p_from_date: fromDate,
p_to_date: toDate,
p_doc_number: docNumber,
p_addres: address,
p_addres_en: addressEN,
p_doc_store: docPath,
p_creator_id: creator,
p_org_id: org
})
};
Then here is my Handle Submit function
const handleSubmit = async (e) => {
e.preventDefault();
const data = new FormData();
data.append('file', selectedFiles);
await fetch(`${config.apiHost}single/`, {
method: 'POST',
body: data
})
.then((res) => res.json())
.then((img) => setDocPath(img.filename))
.catch((err) => {
console.log(err.message);
});
setEditOpen(false);
fetch(`${config.apiHost}api/employees/info/pr_docs/new/`, postOptions);
console.log(postOptions.body);
};
My state docPath stays empty while I'm trying to submit so after that I can't see it in my request.
you can refactor your code to this and lets see if it works;
let postOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${window.localStorage.serviceToken}`
},
body: {
p_emp_id: empId,
p_pr_doc_type: docType,
p_from_date: fromDate,
p_to_date: toDate,
p_doc_number: docNumber,
p_addres: address,
p_addres_en: addressEN,
p_creator_id: creator,
p_org_id: org
}
};
for the handle submit it can be
const handleSubmit = async (e) => {
e.preventDefault();
const data = new FormData();
data.append('file', selectedFiles);
await fetch(`${config.apiHost}single/`, {
method: 'POST',
body: data
})
.then((res) => res.json())
.then((img) => {
const postOptionsBody = {...postOptions.body, p_doc_store : img.filename }
postOptions = {...postOptions, body : JSON.stringify(postOptionsBody) }
setDocPath(img.filename)
})
.catch((err) => {
console.log(err.message);
});
setEditOpen(false);
fetch(`${config.apiHost}api/employees/info/pr_docs/new/`, postOptions);
console.log(postOptions.body);
};
I am trying to upload a file(uploadType=multipart) to Drive API V3 using fetch but the body is wrong as it is creating a file with the title unnamed.
var tmpFile=document.getElementById('inputFile').files;
tmpFile=tmpFile[0];
await fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', {
method: 'POST', // or 'PUT'
headers: {
'Authorization': 'Bearer '+accessToken,
},
body: {
metadata:{
'name':tmpFile.name,
'Content-Type':'application/json; charset=UTF-8'
},
media:{
'Content-Type': '*/*',
'name':tmpFile
}
}
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
Your metadata is not being properly uploaded if its uploading with a name of unnamed
const fs = require("fs");
const FormData = require("form-data");
const fetch = require("node-fetch");
const filePath = "./sample.txt";
const accessToken = "###";
token = req.body.token;
var formData = new FormData();
var fileMetadata = {
name: "sample.txt",
};
formData.append("metadata", JSON.stringify(fileMetadata), {
contentType: "application/json",
});
formData.append("data", fs.createReadStream(filePath), {
filename: "sample.txt",
contentType: "text/plain",
});
fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart", {
method: "POST",
body: formData,
headers: { Authorization: "Bearer " + accessToken },
})
.then((res) => res.json())
.then(console.log);
Uploading Files of multipart/form-data to Google Drive using Drive API with Node.js
I want to retrieve the JSON response from the api call I am doing. Example, I want to retrieve something like this:
{"error":{},"success":true,"data":{"user":"tom","password":"123","skill":"beginner","year":2019,"month":"Mar","day":31,"playmorning":0,"playafternoon":1,"playevening":1}}
This is my API call using fetch in react. (yes I know sending password in URL is bad, it's for a school project)
fetch('/api/user/'+ user + '?password=' + password, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}}).then((res) => {
console.log(res); //I want to get the JSON stuff here
})
This is the API call I am calling.
app.get('/api/user/:user', function (req, res) {
// console.log(JSON.stringify(req));
// var user = req.body.user;
// var password = req.body.password;
var user = req.params.user;
var password = req.query.password;
console.log(user, password);
var result = { error: {} , success:false};
if(user==""){
result["error"]["user"]="user not supplied";
}
if(password==""){
result["error"]["password"]="password not supplied";
}
if(isEmptyObject(result["error"])){
let sql = 'SELECT * FROM user WHERE user=? and password=?;';
db.get(sql, [user, password], function (err, row){
if (err) {
res.status(500);
result["error"]["db"] = err.message;
} else if (row) {
res.status(200);
result.data = row;
result.success = true;
} else {
res.status(401);
result.success = false;
result["error"]["login"] = "login failed";
}
res.json(result);
});
} else {
res.status(400);
res.json(result);
}
});
When I do console.log(res) in the fetch call, this is what is printed:
Response {type: "basic", url: "http://localhost:3000/api/user/tim?password=123", redirected: false, status: 200, ok: true, …}body: (...)bodyUsed: falseheaders: Headers {}ok: trueredirected: falsestatus: 200statusText: "OK"type: "basic"url: "http://localhost:3000/api/user/tim?password=123"proto: Response
When I visit the website, the output is:
{"error":{},"success":true,"data":{"user":"tom","password":"123","skill":"beginner","year":2019,"month":"Mar","day":31,"playmorning":0,"playafternoon":1,"playevening":1}}
This is what I want.
In general, this is how you return the response body from the Promise.
fetch(`${baseUrl}/api/user/${user}?password=${password}`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}})
.then(response => response.json())
.then(data=> {
console.log(data);
})
Try this way to parse the response:
fetch('/api/user/'+ user + '?password=' + password, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}}).then(async (res) => {
const raw = await res.text();
const parsed = raw ? JSON.parse(raw) : { success: res.ok };
console.log(parsed);
})
In this case you can also add some checks for response statuses (if you want, of course) along with parsing the result JSON.
for you to get the JSON body content from the response, you need to use json()
fetch('/api/user/'+ user + '?password=' + password, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}}).then((res) => {
const jsonData = res.json();
console.log(jsonData);
})
try this
fetch(${baseUrl}/api/user/${user}?password=${password},{
method:'GET',
headers: {
'Accept': 'application/json',
'Content-Type':
'application/json',
}}) .then(async(response ) => {
await response.json()
})
$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 trying to put and delete data from a web service via fetch, but I am getting the following error
net::ERR_SPDY_PROTOCOL_ERROR
const Headers = { 'Content-Type': 'application/json', 'Access-Control-Request-Method': '*'};
const url = 'https://tesisweb.000webhostapp.com/genTesis/api/public/coo/1';
const req = new Request(serverUrl + url, {method: 'PUT', headers: Headers, body: obj});
return fetch(req)
.then(status)
.then((response) => {
return response.json();
});
In the BackEnd i using php slim and eloquent
Middelware
$corsOptions = array(
"origin" => "*",
"exposeHeaders" => array("Content-Type", "X-Requested-With", "X-authentication", "X-client"),
"allowMethods" => array('GET', 'POST', 'PUT', 'DELETE', 'OPTIONS')
);
$cors = new \CorsSlim\CorsSlim($corsOptions);
$app->add($cors);