I have access to Exact (OAUTH), access-, refresh-tokens, division No. ...
I get, 'GET' information From Exact API.
But I have problems in 'POST'-ing a new project, using Exact API.
And I have no Clue what is the problem.
As a user, I have 'POST' privileges ().
https://start.exactonline.nl/api/v1/2999609/Users/UserHasRights?endpoint='project/Projects'&action='POST' => true
I've no clue what to do next. Maybe I need to provide more data, but the documentations, state those three fields are enough to create a project.
const data = {
"Code":"P99A",
"Description":"P99A Descr",
"Type": 1
}
const response = await fetch('https://start.exactonline.nl/api/v1/2999609/project/Projects', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Prefer': 'return=representation',
'Authorization': `Bearer ${accessToken}`
},
body: JSON.stringify(data)
})
console.log(response)
Exact Server response:
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: {
body: PassThrough {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: null
},
disturbed: false,
error: null
},
[Symbol(Response internals)]: {
url: 'https://start.exactonline.nl/api/v1/2999609/project/Projects',
status: 500,
statusText: 'Internal Server Error',
headers: Headers { [Symbol(map)]: [Object: null prototype] },
counter: 0
}
}
Please try with a different value for Type : 4 means Non-billable which requires no other fields normally.
API Documentation shows that 1 is for Campaign. That value is not available via UI.
Related
I am trying to make POST request using fetch. I am actually following docs example. Docs Provided curl example to make POST request
curl -X POST https://example.com/upload/01
-d "api_key=948324jkl3h45h"
-d "#path/filename.mp4"
-H "Content-Type: application/x-www-form-urlencoded"
There is .mp4 file in my dir. I wrote a simple script to make POST request using fetch. Here is my code.
const filePath = path.join(__dirname , "/video/video.mp4");
const fileData = fs.createReadStream(filePath);
fetch(url, {
body: `api_key=${API_KEY}&${fileData}`,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: "POST"
}).then(result => {
console.log(result)
})
When I make POST request I am getting this error.
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: {
body: PassThrough {
_readableState: [ReadableState],
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
_writableState: [WritableState],
allowHalfOpen: true,
[Symbol(kCapture)]: false,
[Symbol(kCallback)]: null
},
disturbed: false,
error: null
},
[Symbol(Response internals)]: {
url: 'https:/example.com/upload/01',
status: 415,
statusText: 'Unsupported Media Type',
headers: Headers { [Symbol(map)]: [Object: null prototype] },
counter: 0
}
}
I read file using fs.createReadStream. Is that actually right? If there is something wrong, please point me out. I thought some of my file system getting wrong while reading mp4. I wish someone can help me.
Thank youu.
This code I wrote for post method:
storeRecipes() {
const recipes = this.recipeService.getRecipes();
this.http
.put( 'ng-course-recipe-book-a84eb-default-rtdb.europe-west1.firebased…', recipes )
.subscribe(response => { console.log(response); });
}
Refused to apply style from 'https://fonts.googleapis.com/css?family=' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Access to XMLHttpRequest at 'https://ng-course-recipe-book-a84eb-default-rtdb.europe-west1.firebasedatabase.app/?auth= '' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
core.js:4002 ERROR
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: 'Unknown Error', url: 'https://ng-course-recipe-book-a84eb-default-rtdb.europe-west1.firebasedatabase.app/', ok: false, …}
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: 'error', …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message: "Http failure response for https://ng-course-recipe-book-a84eb-default-rtdb.europe-west1.firebasedatabase.app/: 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: "https://ng-course-recipe-book-a84eb-default-rtdb.europe-west1.firebasedatabase.app/"
[[Prototype]]: HttpResponseBase
I have a simple function to test on my application:
this.$userService.getRestaurantsList(userTemp).then(
response => {
console.log(response);
console.log('FUNCIONOU');
}
);
Because I getting errors when I make this simple post, and is giving me this:
Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
This is not CORS my server is configured fine with CORS.
When we go deep to getRestaurantsList method I have this:
getRestaurantsList(user) {
return axios.post(configMain.MAIN_URL + this.GET_COMPANY_RESTAURANT_LIST_URL, JSON.stringify(user));
}
I want to send data like RAW data with AXIOS but if I use stringify it works the post, but if I use like this
getRestaurantsList(user) {
return axios.post(configMain.MAIN_URL + this.GET_COMPANY_RESTAURANT_LIST_URL, user);
}
Only the JSON data it gives me the error you guy see above, and in my API is just returning the data for testing :
This is from LARAVEL API
public function getAllRestaurants2(Request $request)
{
return $this->sendResponse($request->all(), 'Restaurants retrieved successfully');
}
Some update what I'm working on, if I send like this is working:
return axios.post(configMain.MAIN_URL + this.GET_COMPANY_RESTAURANT_LIST_URL, null, {
params: {
search: user
}
});
Only this approach that is not working:
return axios.post(configMain.MAIN_URL + this.GET_COMPANY_RESTAURANT_LIST_URL, user);
Here is my interceptor using STRINGFY and working fine log:
{
"url": "url",
"method": "post",
"data": "{\"loja\":\"teste\"}",
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/x-www-form-urlencoded"
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1
}
Now the interceptor using the wrong approach:
{
"url": "url",
"method": "post",
"data": "{\"id\":\"\",\"name\":\"Anderson Teste\",\"email\":\"teste#email\",\"client_restaurant_id\":11,\"company_id\":1,\"cpf\":\"\",\"phone\":\"81293932921393\",\"locations\":[],\"password\":\"123mudar\"}",
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=utf-8"
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1
}
Here is my configuration from CORS package :
[
'paths' => ['project/api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
What I'm doing wrong that posting like JSON data format is giving me errors?
you will need to make the getRestaurantsList function asynchronous.
try this code.
getRestaurantsList(user) async {
return await axios.post(configMain.MAIN_URL + this.GET_COMPANY_RESTAURANT_LIST_URL, user);
}
Here's what I did on the react end:
componentDidMount(){
console.log('zzzzzzzzzzz')
fetch('http://localhost:5000/z', {mode: 'no-cors'}).then(res=>{console.log(res)
this.setState(res)})
}
Here's what I did with NodeJS + Express:
app.get('/z', (req, res)=>{
console.log('requested')
res.send({msg: "YEEEEHAW"})
})
The request does go through, but it's not what I wanted (the 'YEEEEHAW' is nowhere to be found in browser console):
Response {type: "opaque", url: "", redirected: false, status: 0, ok: false, …}
type: "opaque"
url: ""
redirected: false
status: 0
ok: false
statusText: ""
headers: Headers
__proto__: Headers
body: (...)
bodyUsed: false
__proto__: Response
type: (...)
url: (...)
redirected: (...)
status: (...)
ok: (...)
statusText: (...)
.......
What did I do wrong here? How can I fix it? (To be clear, I did look through + expand every expandable field in the logged object so I'm pretty sure I didn't miss it)
To read response content, you can use res.json():
componentDidMount(){
console.log('zzzzzzzzzzz')
fetch('http://localhost:5000/z', {mode: 'no-cors'})
.then(res=>res.json())
.then(res=>{
console.log(res)
this.setState(res)
})
}
For return a json replace
res.send({msg: "YEEEEHAW"})
for
res.json({msg: "YEEEEHAW"})
In postman, I can successfully make this request:
And get this response:
Now I want to do the same request in my server.js file in node.js:
const fetch = require('node-fetch')
const SEN_URL = "http://www.sentiment140.com/api/bulkClassifyJson" // URL of sentiment analysis
app.get('/api/sentimenttest', async (req, res) => {
try{
var sentiments = await fetch(SEN_URL, {method: "POST", body: {"data": [{"text": "I love you"}, {"text": "I hate you"}]}})
console.log(sentiments)
res.send(sentiments)
}catch(error){
console.log(error)
}
})
This doesn't work. Here's what shows up in the browser when I go to localhost:5000/api/sentimenttest:
{"size":0,"timeout":0}
and here's the console output:
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]:
{ body:
PassThrough {
_readableState: [ReadableState],
readable: true,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: true,
_transformState: [Object] },
disturbed: false,
error: null },
[Symbol(Response internals)]:
{ url: 'http://www.sentiment140.com/api/bulkClassifyJson',
status: 200,
statusText: 'OK',
headers: Headers { [Symbol(map)]: [Object] } } }
Since the request works just fine in postman, I think that the problem is with node-fetch, or the way that I use it, specifically how the body parameter is provided in the fetch() call. It seems like the API call does not contain what I want it to, since in the browser it says "size":0.
What should I do to fix this?
You need to await for json.
var sentiments = await fetch(SEN_URL, {method: "POST", body: {"data": [{"text": "I love you"}, {"text": "I hate you"}]}})
//Here
await sentiments.json()
Also you can make request with JSON.stringify() for body. And it will be easier to manage your js object. Like this:
var data = {data: [{text: "I love you"}, {text: "I hate you"}]};
var body = JSON.stringify(data);
var sentiments = await fetch(SEN_URL, { method: "POST", body: body });
Since it can be easily overlooked within the accepted best answer, just wanted to point out that it's especially crucial to return the response as response.json(). The await part can all be in place correctly and still result in OP's Response { size: 0, timeout: 0 etc } if the .json() method is left off. This whole thread is about POST requests but the same applies to GET etc too.